home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / getopvac.zip / getopt.c next >
Text File  |  2001-03-02  |  32KB  |  937 lines

  1. #define TEST
  2.  
  3. /* Getopt for GNU.
  4.    NOTE: getopt is now part of the C library, so if you don't know what
  5.    "Keep this file name-space clean" means, talk to drepper@gnu.org
  6.    before changing it!
  7.  
  8.    Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98
  9.        Free Software Foundation, Inc.
  10.  
  11.    The GNU C Library is free software; you can redistribute it and/or
  12.    modify it under the terms of the GNU Library General Public License as
  13.    published by the Free Software Foundation; either version 2 of the
  14.    License, or (at your option) any later version.
  15.  
  16.    The GNU C Library is distributed in the hope that it will be useful,
  17.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  18.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  19.    Library General Public License for more details.
  20.  
  21.    You should have received a copy of the GNU Library General Public
  22.    License along with the GNU C Library; see the file COPYING.LIB.  If not,
  23.    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  24.    Boston, MA 02111-1307, USA.
  25. */
  26.  
  27.  
  28.  #include <stdio.h>
  29.  #include <stdlib.h>
  30.  #include <string.h>
  31.  
  32.  
  33. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  34.    but it behaves differently for the user, since it allows the user
  35.    to intersperse the options with the other arguments.
  36.  
  37.    As `getopt' works, it permutes the elements of ARGV so that,
  38.    when it is done, all the options precede everything else.  Thus
  39.    all application programs are extended to handle flexible argument order.
  40.  
  41.    Setting the environment variable POSIXLY_CORRECT disables permutation.
  42.    Then the behavior is completely standard.
  43.  
  44.    GNU application programs can use a third alternative mode in which
  45.    they can distinguish the relative order of options and other arguments.  */
  46.  
  47. #include "getopt.h"
  48.  
  49. /* For communication from `getopt' to the caller.
  50.    When `getopt' finds an option that takes an argument,
  51.    the argument value is returned here.
  52.    Also, when `ordering' is RETURN_IN_ORDER,
  53.    each non-option ARGV-element is returned here.  */
  54.  
  55. char *optarg = NULL;
  56.  
  57. /* Index in ARGV of the next element to be scanned.
  58.    This is used for communication to and from the caller
  59.    and for communication between successive calls to `getopt'.
  60.  
  61.    On entry to `getopt', zero means this is the first call; initialize.
  62.  
  63.    When `getopt' returns -1, this is the index of the first of the
  64.    non-option elements that the caller should itself scan.
  65.  
  66.    Otherwise, `optind' communicates from one call to the next
  67.    how much of ARGV has been scanned so far.  */
  68.  
  69. /* 1003.2 says this must be 1 before any call.  */
  70. int optind = 1;
  71.  
  72. /* Formerly, initialization of getopt depended on optind==0, which
  73.    causes problems with re-calling getopt as programs generally don't
  74.    know that. */
  75.  
  76. int __getopt_initialized = 0;
  77.  
  78. /* The next char to be scanned in the option-element
  79.    in which the last option character we returned was found.
  80.    This allows us to pick up the scan where we left off.
  81.  
  82.    If this is zero, or a null string, it means resume the scan
  83.    by advancing to the next ARGV-element.  */
  84.  
  85. static char *nextchar;
  86.  
  87. /* Callers store zero here to inhibit the error message
  88.    for unrecognized options.  */
  89.  
  90. int opterr = 1;
  91.  
  92. /* Set to an option character which was unrecognized.
  93.    This must be initialized on some systems to avoid linking in the
  94.    system's own getopt implementation.  */
  95.  
  96. int optopt = '?';
  97.  
  98. /* Describe how to deal with options that follow non-option ARGV-elements.
  99.  
  100.    If the caller did not specify anything,
  101.    the default is REQUIRE_ORDER if the environment variable
  102.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  103.  
  104.    REQUIRE_ORDER means don't recognize them as options;
  105.    stop option processing when the first non-option is seen.
  106.    This is what Unix does.
  107.    This mode of operation is selected by either setting the environment
  108.    variable POSIXLY_CORRECT, or using `+' as the first character
  109.    of the list of option characters.
  110.  
  111.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  112.    so that eventually all the non-options are at the end.  This allows options
  113.    to be given in any order, even with programs that were not written to
  114.    expect this.
  115.  
  116.    RETURN_IN_ORDER is an option available to programs that were written
  117.    to expect options and other ARGV-elements in any order and that care about
  118.    the ordering of the two.  We describe each non-option ARGV-element
  119.    as if it were the argument of an option with character code 1.
  120.    Using `-' as the first character of the list of option characters
  121.    selects this mode of operation.
  122.  
  123.    The special argument `--' forces an end of option-scanning regardless
  124.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  125.    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
  126.  
  127. static enum
  128. {
  129.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  130. } ordering;
  131.  
  132. /* Value of POSIXLY_CORRECT environment variable.  */
  133. static char *posixly_correct;
  134.  
  135. #define        my_index        strchr
  136. # define _(msgid) (msgid)
  137.  
  138.  
  139. /* Handle permutation of arguments.  */
  140.  
  141. /* Describe the part of ARGV that contains non-options that have
  142.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  143.    `last_nonopt' is the index after the last of them.  */
  144.  
  145. static int first_nonopt;
  146. static int last_nonopt;
  147.  
  148. #ifdef _LIBC
  149. /* Bash 2.0 gives us an environment variable containing flags
  150.    indicating ARGV elements that should not be considered arguments.  */
  151.  
  152. /* Defined in getopt_init.c  */
  153. extern char *__getopt_nonoption_flags;
  154.  
  155. static int nonoption_flags_max_len;
  156. static int nonoption_flags_len;
  157.  
  158. static int original_argc;
  159. static char *const *original_argv;
  160.  
  161. /* Make sure the environment variable bash 2.0 puts in the environment
  162.    is valid for the getopt call we must make sure that the ARGV passed
  163.    to getopt is that one passed to the process.  */
  164. static void
  165. __attribute__ ((unused))
  166. store_args_and_env (int argc, char *const *argv)
  167. {
  168.   /* XXX This is no good solution.  We should rather copy the args so
  169.      that we can compare them later.  But we must not use malloc(3).  */
  170.   original_argc = argc;
  171.   original_argv = argv;
  172. }
  173. # ifdef text_set_element
  174.   text_set_element (__libc_subinit, store_args_and_env);
  175. # endif /* text_set_element */
  176.  
  177. # define SWAP_FLAGS(ch1, ch2) \
  178.   if (nonoption_flags_len > 0)                                               \
  179.     {                                                                        \
  180.       char __tmp = __getopt_nonoption_flags[ch1];                            \
  181.       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];         \
  182.       __getopt_nonoption_flags[ch2] = __tmp;                                 \
  183.     }
  184. #else  /* !_LIBC */
  185.   # define SWAP_FLAGS(ch1, ch2)
  186. #endif /* _LIBC */
  187.  
  188. /* Exchange two adjacent subsequences of ARGV.
  189.    One subsequence is elements [first_nonopt,last_nonopt)
  190.    which contains all the non-options that have been skipped so far.
  191.    The other is elements [last_nonopt,optind), which contains all
  192.    the options processed since those non-options were skipped.
  193.  
  194.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  195.    the new indices of the non-options in ARGV after they are moved.  */
  196.  
  197. #if defined __STDC__ && __STDC__
  198.    static void exchange (char **);
  199. #endif
  200.  
  201. static void
  202. exchange (char **argv)
  203. {
  204.   int bottom = first_nonopt;
  205.   int middle = last_nonopt;
  206.   int top = optind;
  207.   char *tem;
  208.  
  209.   /* Exchange the shorter segment with the far end of the longer segment.
  210.      That puts the shorter segment into the right place.
  211.      It leaves the longer segment in the right place overall,
  212.      but it consists of two parts that need to be swapped next.  */
  213.  
  214. #ifdef _LIBC
  215.   /* First make sure the handling of the `__getopt_nonoption_flags'
  216.      string can work normally.  Our top argument must be in the range
  217.      of the string.  */
  218.   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  219.     {
  220.       /* We must extend the array.  The user plays games with us and
  221.         presents new arguments.  */
  222.       char *new_str = malloc (top + 1);
  223.       if (new_str == NULL)
  224.        nonoption_flags_len = nonoption_flags_max_len = 0;
  225.       else
  226.        {
  227.          memset (__mempcpy (new_str, __getopt_nonoption_flags,
  228.                             nonoption_flags_max_len),
  229.                  '\0', top + 1 - nonoption_flags_max_len);
  230.          nonoption_flags_max_len = top + 1;
  231.          __getopt_nonoption_flags = new_str;
  232.        }
  233.     }
  234. #endif
  235.  
  236.   while (top > middle && middle > bottom)
  237.     {
  238.       if (top - middle > middle - bottom)
  239.        {
  240.          /* Bottom segment is the short one.  */
  241.          int len = middle - bottom;
  242.          register int i;
  243.  
  244.          /* Swap it with the top part of the top segment.  */
  245.          for (i = 0; i < len; i++)
  246.            {
  247.              tem = argv[bottom + i];
  248.              argv[bottom + i] = argv[top - (middle - bottom) + i];
  249.              argv[top - (middle - bottom) + i] = tem;
  250.              SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  251.            }
  252.          /* Exclude the moved bottom segment from further swapping.  */
  253.          top -= len;
  254.        }
  255.       else
  256.        {
  257.          /* Top segment is the short one.  */
  258.          int len = top - middle;
  259.          register int i;
  260.  
  261.          /* Swap it with the bottom part of the bottom segment.  */
  262.          for (i = 0; i < len; i++)
  263.            {
  264.              tem = argv[bottom + i];
  265.              argv[bottom + i] = argv[middle + i];
  266.              argv[middle + i] = tem;
  267.              SWAP_FLAGS (bottom + i, middle + i);
  268.            }
  269.          /* Exclude the moved top segment from further swapping.  */
  270.          bottom += len;
  271.        }
  272.     }
  273.  
  274.   /* Update records for the slots the non-options now occupy.  */
  275.  
  276.   first_nonopt += (optind - last_nonopt);
  277.   last_nonopt = optind;
  278. }
  279.  
  280. /* Initialize the internal data when the first call is made.  */
  281.  
  282. #if defined __STDC__ && __STDC__
  283.   static const char *_getopt_initialize (int, char *const *, const char *);
  284. #endif
  285.  
  286. static const char *
  287. _getopt_initialize (int argc, char *const *argv, const char *optstring)
  288. {
  289.   /* Start processing options with ARGV-element 1 (since ARGV-element 0
  290.      is the program name); the sequence of previously skipped
  291.      non-option ARGV-elements is empty.  */
  292.  
  293.   first_nonopt = last_nonopt = optind;
  294.  
  295.   nextchar = NULL;
  296.  
  297.   posixly_correct = getenv ("POSIXLY_CORRECT");
  298.  
  299.   /* Determine how to handle the ordering of options and nonoptions.  */
  300.  
  301.   if (optstring[0] == '-')
  302.     {
  303.       ordering = RETURN_IN_ORDER;
  304.       ++optstring;
  305.     }
  306.   else if (optstring[0] == '+')
  307.     {
  308.       ordering = REQUIRE_ORDER;
  309.       ++optstring;
  310.     }
  311.   else if (posixly_correct != NULL)
  312.     ordering = REQUIRE_ORDER;
  313.   else
  314.     ordering = PERMUTE;
  315.  
  316. #ifdef _LIBC
  317.   if (posixly_correct == NULL
  318.       && argc == original_argc && argv == original_argv)
  319.     {
  320.       if (nonoption_flags_max_len == 0)
  321.        {
  322.          if (__getopt_nonoption_flags == NULL
  323.              || __getopt_nonoption_flags[0] == '\0')
  324.            nonoption_flags_max_len = -1;
  325.          else
  326.            {
  327.              const char *orig_str = __getopt_nonoption_flags;
  328.              int len = nonoption_flags_max_len = strlen (orig_str);
  329.              if (nonoption_flags_max_len < argc)
  330.                nonoption_flags_max_len = argc;
  331.              __getopt_nonoption_flags =
  332.                (char *) malloc (nonoption_flags_max_len);
  333.              if (__getopt_nonoption_flags == NULL)
  334.                nonoption_flags_max_len = -1;
  335.              else
  336.                memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
  337.                        '\0', nonoption_flags_max_len - len);
  338.            }
  339.        }
  340.       nonoption_flags_len = nonoption_flags_max_len;
  341.     }
  342.   else
  343.     nonoption_flags_len = 0;
  344. #endif
  345.  
  346.   return optstring;
  347. }
  348.  
  349. /* Scan elements of ARGV (whose length is ARGC) for option characters
  350.    given in OPTSTRING.
  351.  
  352.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  353.    then it is an option element.  The characters of this element
  354.    (aside from the initial '-') are option characters.  If `getopt'
  355.    is called repeatedly, it returns successively each of the option characters
  356.    from each of the option elements.
  357.  
  358.    If `getopt' finds another option character, it returns that character,
  359.    updating `optind' and `nextchar' so that the next call to `getopt' can
  360.    resume the scan with the following option character or ARGV-element.
  361.  
  362.    If there are no more option characters, `getopt' returns -1.
  363.    Then `optind' is the index in ARGV of the first ARGV-element
  364.    that is not an option.  (The ARGV-elements have been permuted
  365.    so that those that are not options now come last.)
  366.  
  367.    OPTSTRING is a string containing the legitimate option characters.
  368.    If an option character is seen that is not listed in OPTSTRING,
  369.    return '?' after printing an error message.  If you set `opterr' to
  370.    zero, the error message is suppressed but we still return '?'.
  371.  
  372.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  373.    so the following text in the same ARGV-element, or the text of the following
  374.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  375.    wants an optional arg; if there is text in the current ARGV-element,
  376.    it is returned in `optarg', otherwise `optarg' is set to zero.
  377.  
  378.    If OPTSTRING starts with `-' or `+', it requests different methods of
  379.    handling the non-option ARGV-elements.
  380.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  381.  
  382.    Long-named options begin with `--' instead of `-'.
  383.    Their names may be abbreviated as long as the abbreviation is unique
  384.    or is an exact match for some defined option.  If they have an
  385.    argument, it follows the option name in the same ARGV-element, separated
  386.    from the option name by a `=', or else the in next ARGV-element.
  387.    When `getopt' finds a long-named option, it returns 0 if that option's
  388.    `flag' field is nonzero, the value of the option's `val' field
  389.    if the `flag' field is zero.
  390.  
  391.    The elements of ARGV aren't really const, because we permute them.
  392.    But we pretend they're const in the prototype to be compatible
  393.    with other systems.
  394.  
  395.    LONGOPTS is a vector of `struct option' terminated by an
  396.    element containing a name which is zero.
  397.  
  398.    LONGIND returns the index in LONGOPT of the long-named option found.
  399.    It is only valid when a long-named option has been found by the most
  400.    recent call.
  401.  
  402.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  403.    long-named options.  */
  404.  
  405. int
  406. _getopt_internal (int argc, char *const * argv, const char *optstring,
  407.                   const struct option *longopts, int *longind, int long_only)
  408. {
  409.   optarg = NULL;
  410.  
  411.   if (optind == 0 || !__getopt_initialized)
  412.     {
  413.       if (optind == 0)
  414.        optind = 1;     /* Don't scan ARGV[0], the program name.  */
  415.       optstring = _getopt_initialize (argc, argv, optstring);
  416.       __getopt_initialized = 1;
  417.     }
  418.  
  419.   /* Test whether ARGV[optind] points to a non-option argument.
  420.      Either it does not have option syntax, or there is an environment flag
  421.      from the shell indicating it is not an option.  The later information
  422.      is only used when the used in the GNU libc.  */
  423. #ifdef _LIBC
  424. #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
  425.                     || (optind < nonoption_flags_len                         \
  426.                         && __getopt_nonoption_flags[optind] == '1'))
  427. #else
  428. #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  429. #endif
  430.  
  431.   if (nextchar == NULL || *nextchar == '\0')
  432.     {
  433.       /* Advance to the next ARGV-element.  */
  434.  
  435.       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  436.         moved back by the user (who may also have changed the arguments).  */
  437.       if (last_nonopt > optind)
  438.        last_nonopt = optind;
  439.       if (first_nonopt > optind)
  440.        first_nonopt = optind;
  441.  
  442.       if (ordering == PERMUTE)
  443.        {
  444.          /* If we have just processed some options following some non-options,
  445.             exchange them so that the options come first.  */
  446.  
  447.          if (first_nonopt != last_nonopt && last_nonopt != optind)
  448.            exchange ((char **) argv);
  449.          else if (last_nonopt != optind)
  450.            first_nonopt = optind;
  451.  
  452.          /* Skip any additional non-options
  453.             and extend the range of non-options previously skipped.  */
  454.  
  455.          while (optind < argc && NONOPTION_P)
  456.            optind++;
  457.          last_nonopt = optind;
  458.        }
  459.  
  460.       /* The special ARGV-element `--' means premature end of options.
  461.         Skip it like a null option,
  462.         then exchange with previous non-options as if it were an option,
  463.         then skip everything else like a non-option.  */
  464.  
  465.       if (optind != argc && !strcmp (argv[optind], "--"))
  466.        {
  467.          optind++;
  468.  
  469.          if (first_nonopt != last_nonopt && last_nonopt != optind)
  470.            exchange ((char **) argv);
  471.          else if (first_nonopt == last_nonopt)
  472.            first_nonopt = optind;
  473.          last_nonopt = argc;
  474.  
  475.          optind = argc;
  476.        }
  477.  
  478.       /* If we have done all the ARGV-elements, stop the scan
  479.         and back over any non-options that we skipped and permuted.  */
  480.  
  481.       if (optind == argc)
  482.        {
  483.          /* Set the next-arg-index to point at the non-options
  484.             that we previously skipped, so the caller will digest them.  */
  485.          if (first_nonopt != last_nonopt)
  486.            optind = first_nonopt;
  487.          return -1;
  488.        }
  489.  
  490.       /* If we have come to a non-option and did not permute it,
  491.         either stop the scan or describe it to the caller and pass it by.  */
  492.  
  493.       if (NONOPTION_P)
  494.        {
  495.          if (ordering == REQUIRE_ORDER)
  496.            return -1;
  497.          optarg = argv[optind++];
  498.          return 1;
  499.        }
  500.  
  501.       /* We have found another option-ARGV-element.
  502.         Skip the initial punctuation.  */
  503.  
  504.       nextchar = (argv[optind] + 1
  505.                  + (longopts != NULL && argv[optind][1] == '-'));
  506.     }
  507.  
  508.   /* Decode the current option-ARGV-element.  */
  509.  
  510.   /* Check whether the ARGV-element is a long option.
  511.  
  512.      If long_only and the ARGV-element has the form "-f", where f is
  513.      a valid short option, don't consider it an abbreviated form of
  514.      a long option that starts with f.  Otherwise there would be no
  515.      way to give the -f short option.
  516.  
  517.      On the other hand, if there's a long option "fubar" and
  518.      the ARGV-element is "-fu", do consider that an abbreviation of
  519.      the long option, just like "--fu", and not "-f" with arg "u".
  520.  
  521.      This distinction seems to be the most useful approach.  */
  522.  
  523.   if (longopts != NULL
  524.       && (argv[optind][1] == '-'
  525.          || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
  526.     {
  527.       char *nameend;
  528.       const struct option *p;
  529.       const struct option *pfound = NULL;
  530.       int exact = 0;
  531.       int ambig = 0;
  532.       int indfound = -1;
  533.       int option_index;
  534.  
  535.       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  536.        /* Do nothing.  */ ;
  537.  
  538.       /* Test all long options for either exact match
  539.         or abbreviated matches.  */
  540.       for (p = longopts, option_index = 0; p->name; p++, option_index++)
  541.        if (!strncmp (p->name, nextchar, nameend - nextchar))
  542.          {
  543.            if ((unsigned int) (nameend - nextchar)
  544.                == (unsigned int) strlen (p->name))
  545.              {
  546.                /* Exact match found.  */
  547.                pfound = p;
  548.                indfound = option_index;
  549.                exact = 1;
  550.                break;
  551.              }
  552.            else if (pfound == NULL)
  553.              {
  554.                /* First nonexact match found.  */
  555.                pfound = p;
  556.                indfound = option_index;
  557.              }
  558.            else
  559.              /* Second or later nonexact match found.  */
  560.              ambig = 1;
  561.          }
  562.  
  563.       if (ambig && !exact)
  564.        {
  565.          if (opterr)
  566.            fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
  567.                     argv[0], argv[optind]);
  568.          nextchar += strlen (nextchar);
  569.          optind++;
  570.          optopt = 0;
  571.          return '?';
  572.        }
  573.  
  574.       if (pfound != NULL)
  575.        {
  576.          option_index = indfound;
  577.          optind++;
  578.          if (*nameend)
  579.            {
  580.              /* Don't test has_arg with >, because some C compilers don't
  581.                 allow it to be used on enums.  */
  582.              if (pfound->has_arg)
  583.                optarg = nameend + 1;
  584.              else
  585.                {
  586.                  if (opterr)
  587.                   if (argv[optind - 1][1] == '-')
  588.                    /* --option */
  589.                    fprintf (stderr,
  590.                     _("%s: option `--%s' doesn't allow an argument\n"),
  591.                     argv[0], pfound->name);
  592.                   else
  593.                    /* +option or -option */
  594.                    fprintf (stderr,
  595.                     _("%s: option `%c%s' doesn't allow an argument\n"),
  596.                     argv[0], argv[optind - 1][0], pfound->name);
  597.  
  598.                  nextchar += strlen (nextchar);
  599.  
  600.                  optopt = pfound->val;
  601.                  return '?';
  602.                }
  603.            }
  604.          else if (pfound->has_arg == 1)
  605.            {
  606.              if (optind < argc)
  607.                optarg = argv[optind++];
  608.              else
  609.                {
  610.                  if (opterr)
  611.                    fprintf (stderr,
  612.                           _("%s: option `%s' requires an argument\n"),
  613.                           argv[0], argv[optind - 1]);
  614.                  nextchar += strlen (nextchar);
  615.                  optopt = pfound->val;
  616.                  return optstring[0] == ':' ? ':' : '?';
  617.                }
  618.            }
  619.          nextchar += strlen (nextchar);
  620.          if (longind != NULL)
  621.            *longind = option_index;
  622.          if (pfound->flag)
  623.            {
  624.              *(pfound->flag) = pfound->val;
  625.              return 0;
  626.            }
  627.          return pfound->val;
  628.        }
  629.  
  630.       /* Can't find it as a long option.  If this is not getopt_long_only,
  631.         or the option starts with '--' or is not a valid short
  632.         option, then it's an error.
  633.         Otherwise interpret it as a short option.  */
  634.       if (!long_only || argv[optind][1] == '-'
  635.          || my_index (optstring, *nextchar) == NULL)
  636.        {
  637.          if (opterr)
  638.            {
  639.              if (argv[optind][1] == '-')
  640.                /* --option */
  641.                fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
  642.                         argv[0], nextchar);
  643.              else
  644.                /* +option or -option */
  645.                fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
  646.                         argv[0], argv[optind][0], nextchar);
  647.            }
  648.          nextchar = (char *) "";
  649.          optind++;
  650.          optopt = 0;
  651.          return '?';
  652.        }
  653.     }
  654.  
  655.   /* Look at and handle the next short option-character.  */
  656.  
  657.   {
  658.     char c = *nextchar++;
  659.     char *temp = my_index (optstring, c);
  660.  
  661.     /* Increment `optind' when we start to process its last character.  */
  662.     if (*nextchar == '\0')
  663.       ++optind;
  664.  
  665.     if (temp == NULL || c == ':')
  666.       {
  667.        if (opterr)
  668.          {
  669.            if (posixly_correct)
  670.              /* 1003.2 specifies the format of this message.  */
  671.              fprintf (stderr, _("%s: illegal option -- %c\n"),
  672.                       argv[0], c);
  673.            else
  674.              fprintf (stderr, _("%s: invalid option -- %c\n"),
  675.                       argv[0], c);
  676.          }
  677.        optopt = c;
  678.        return '?';
  679.       }
  680.     /* Convenience. Treat POSIX -W foo same as long option --foo */
  681.     if (temp[0] == 'W' && temp[1] == ';')
  682.       {
  683.        char *nameend;
  684.        const struct option *p;
  685.        const struct option *pfound = NULL;
  686.        int exact = 0;
  687.        int ambig = 0;
  688.        int indfound = 0;
  689.        int option_index;
  690.  
  691.        /* This is an option that requires an argument.  */
  692.        if (*nextchar != '\0')
  693.          {
  694.            optarg = nextchar;
  695.            /* If we end this ARGV-element by taking the rest as an arg,
  696.               we must advance to the next element now.  */
  697.            optind++;
  698.          }
  699.        else if (optind == argc)
  700.          {
  701.            if (opterr)
  702.              {
  703.                /* 1003.2 specifies the format of this message.  */
  704.                fprintf (stderr, _("%s: option requires an argument -- %c\n"),
  705.                         argv[0], c);
  706.              }
  707.            optopt = c;
  708.            if (optstring[0] == ':')
  709.              c = ':';
  710.            else
  711.              c = '?';
  712.            return c;
  713.          }
  714.        else
  715.          /* We already incremented `optind' once;
  716.             increment it again when taking next ARGV-elt as argument.  */
  717.          optarg = argv[optind++];
  718.  
  719.        /* optarg is now the argument, see if it's in the
  720.           table of longopts.  */
  721.  
  722.        for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  723.          /* Do nothing.  */ ;
  724.  
  725.        /* Test all long options for either exact match
  726.           or abbreviated matches.  */
  727.        for (p = longopts, option_index = 0; p->name; p++, option_index++)
  728.          if (!strncmp (p->name, nextchar, nameend - nextchar))
  729.            {
  730.              if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  731.                {
  732.                  /* Exact match found.  */
  733.                  pfound = p;
  734.                  indfound = option_index;
  735.                  exact = 1;
  736.                  break;
  737.                }
  738.              else if (pfound == NULL)
  739.                {
  740.                  /* First nonexact match found.  */
  741.                  pfound = p;
  742.                  indfound = option_index;
  743.                }
  744.              else
  745.                /* Second or later nonexact match found.  */
  746.                ambig = 1;
  747.            }
  748.        if (ambig && !exact)
  749.          {
  750.            if (opterr)
  751.              fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
  752.                       argv[0], argv[optind]);
  753.            nextchar += strlen (nextchar);
  754.            optind++;
  755.            return '?';
  756.          }
  757.        if (pfound != NULL)
  758.          {
  759.            option_index = indfound;
  760.            if (*nameend)
  761.              {
  762.                /* Don't test has_arg with >, because some C compilers don't
  763.                   allow it to be used on enums.  */
  764.                if (pfound->has_arg)
  765.                  optarg = nameend + 1;
  766.                else
  767.                  {
  768.                    if (opterr)
  769.                      fprintf (stderr, _("\
  770. %s: option `-W %s' doesn't allow an argument\n"),
  771.                               argv[0], pfound->name);
  772.  
  773.                    nextchar += strlen (nextchar);
  774.                    return '?';
  775.                  }
  776.              }
  777.            else if (pfound->has_arg == 1)
  778.              {
  779.                if (optind < argc)
  780.                  optarg = argv[optind++];
  781.                else
  782.                  {
  783.                    if (opterr)
  784.                      fprintf (stderr,
  785.                               _("%s: option `%s' requires an argument\n"),
  786.                               argv[0], argv[optind - 1]);
  787.                    nextchar += strlen (nextchar);
  788.                    return optstring[0] == ':' ? ':' : '?';
  789.                  }
  790.              }
  791.            nextchar += strlen (nextchar);
  792.            if (longind != NULL)
  793.              *longind = option_index;
  794.            if (pfound->flag)
  795.              {
  796.                *(pfound->flag) = pfound->val;
  797.                return 0;
  798.              }
  799.            return pfound->val;
  800.          }
  801.          nextchar = NULL;
  802.          return 'W';   /* Let the application handle it.   */
  803.       }
  804.     if (temp[1] == ':')
  805.       {
  806.        if (temp[2] == ':')
  807.          {
  808.            /* This is an option that accepts an argument optionally.  */
  809.            if (*nextchar != '\0')
  810.              {
  811.                optarg = nextchar;
  812.                optind++;
  813.              }
  814.            else
  815.              optarg = NULL;
  816.            nextchar = NULL;
  817.          }
  818.        else
  819.          {
  820.            /* This is an option that requires an argument.  */
  821.            if (*nextchar != '\0')
  822.              {
  823.                optarg = nextchar;
  824.                /* If we end this ARGV-element by taking the rest as an arg,
  825.                   we must advance to the next element now.  */
  826.                optind++;
  827.              }
  828.            else if (optind == argc)
  829.              {
  830.                if (opterr)
  831.                  {
  832.                    /* 1003.2 specifies the format of this message.  */
  833.                    fprintf (stderr,
  834.                           _("%s: option requires an argument -- %c\n"),
  835.                           argv[0], c);
  836.                  }
  837.                optopt = c;
  838.                if (optstring[0] == ':')
  839.                  c = ':';
  840.                else
  841.                  c = '?';
  842.              }
  843.            else
  844.              /* We already incremented `optind' once;
  845.                 increment it again when taking next ARGV-elt as argument.  */
  846.              optarg = argv[optind++];
  847.            nextchar = NULL;
  848.          }
  849.       }
  850.     return c;
  851.   }
  852. }
  853.  
  854. int
  855. getopt (argc, argv, optstring)
  856.      int argc;
  857.      char *const *argv;
  858.      const char *optstring;
  859. {
  860.   return _getopt_internal (argc, argv, optstring,
  861.                           (const struct option *) 0,
  862.                           (int *) 0,
  863.                           0);
  864. }
  865.  
  866. #ifdef TEST
  867.  
  868. /* Compile with -DTEST to make an executable for use in testing
  869.    the above definition of `getopt'.  */
  870.  
  871. int
  872. main (argc, argv)
  873.      int argc;
  874.      char **argv;
  875. {
  876.   int c;
  877.   int digit_optind = 0;
  878.  
  879.   while (1)
  880.     {
  881.       int this_option_optind = optind ? optind : 1;
  882.  
  883.       c = getopt (argc, argv, "abc:d:0123456789");
  884.       if (c == -1)
  885.        break;
  886.  
  887.       switch (c)
  888.        {
  889.        case '0':
  890.        case '1':
  891.        case '2':
  892.        case '3':
  893.        case '4':
  894.        case '5':
  895.        case '6':
  896.        case '7':
  897.        case '8':
  898.        case '9':
  899.          if (digit_optind != 0 && digit_optind != this_option_optind)
  900.            printf ("digits occur in two different argv-elements.\n");
  901.          digit_optind = this_option_optind;
  902.          printf ("option %c\n", c);
  903.          break;
  904.  
  905.        case 'a':
  906.          printf ("option a\n");
  907.          break;
  908.  
  909.        case 'b':
  910.          printf ("option b\n");
  911.          break;
  912.  
  913.        case 'c':
  914.          printf ("option c with value `%s'\n", optarg);
  915.          break;
  916.  
  917.        case '?':
  918.          break;
  919.  
  920.        default:
  921.          printf ("?? getopt returned character code 0%o ??\n", c);
  922.        }
  923.     }
  924.  
  925.   if (optind < argc)
  926.     {
  927.       printf ("non-option ARGV-elements: ");
  928.       while (optind < argc)
  929.        printf ("%s ", argv[optind++]);
  930.       printf ("\n");
  931.     }
  932.  
  933.   exit (0);
  934. }
  935.  
  936. #endif /* TEST */
  937.