1/* argmatch.c -- find a match for a string in an array
2   Copyright (C) 1990 Free Software Foundation, Inc.
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2, or (at your option)
7   any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.  */
13
14/* Written by David MacKenzie <djm@ai.mit.edu> */
15
16#ifdef HAVE_CONFIG_H
17#include "config.h"
18#endif
19
20#include <sys/types.h>
21
22#include <stdio.h>
23#ifdef STDC_HEADERS
24#include <string.h>
25#endif
26
27extern char *program_name;
28
29/* If ARG is an unambiguous match for an element of the
30   null-terminated array OPTLIST, return the index in OPTLIST
31   of the matched element, else -1 if it does not match any element
32   or -2 if it is ambiguous (is a prefix of more than one element). */
33
34int
35argmatch (arg, optlist)
36     char *arg;
37     char **optlist;
38{
39  int i;			/* Temporary index in OPTLIST. */
40  size_t arglen;		/* Length of ARG. */
41  int matchind = -1;		/* Index of first nonexact match. */
42  int ambiguous = 0;		/* If nonzero, multiple nonexact match(es). */
43
44  arglen = strlen (arg);
45
46  /* Test all elements for either exact match or abbreviated matches.  */
47  for (i = 0; optlist[i]; i++)
48    {
49      if (!strncmp (optlist[i], arg, arglen))
50	{
51	  if (strlen (optlist[i]) == arglen)
52	    /* Exact match found.  */
53	    return i;
54	  else if (matchind == -1)
55	    /* First nonexact match found.  */
56	    matchind = i;
57	  else
58	    /* Second nonexact match found.  */
59	    ambiguous = 1;
60	}
61    }
62  if (ambiguous)
63    return -2;
64  else
65    return matchind;
66}
67
68/* Error reporting for argmatch.
69   KIND is a description of the type of entity that was being matched.
70   VALUE is the invalid value that was given.
71   PROBLEM is the return value from argmatch. */
72
73void
74invalid_arg (kind, value, problem)
75     char *kind;
76     char *value;
77     int problem;
78{
79  fprintf (stderr, "%s: ", program_name);
80  if (problem == -1)
81    fprintf (stderr, "invalid");
82  else				/* Assume -2. */
83    fprintf (stderr, "ambiguous");
84  fprintf (stderr, " %s `%s'\n", kind, value);
85}
86