1/*	$OpenBSD: getoldopt.c,v 1.9 2009/10/27 23:59:22 deraadt Exp $	*/
2/*	$NetBSD: getoldopt.c,v 1.3 1995/03/21 09:07:28 cgd Exp $	*/
3
4/*-
5 * Plug-compatible replacement for getopt() for parsing tar-like
6 * arguments.  If the first argument begins with "-", it uses getopt;
7 * otherwise, it uses the old rules used by tar, dump, and ps.
8 *
9 * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed
10 * in the Public Domain for your edification and enjoyment.
11 */
12
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <stdio.h>
16#include <string.h>
17#include <unistd.h>
18
19int getoldopt(int, char **, const char *);
20
21int
22getoldopt(int argc, char **argv, const char *optstring)
23{
24	static char	*key;		/* Points to next keyletter */
25	static char	use_getopt;	/* !=0 if argv[1][0] was '-' */
26	char		c;
27	char		*place;
28
29	optarg = NULL;
30
31	if (key == NULL) {		/* First time */
32		if (argc < 2)
33			return (-1);
34		key = argv[1];
35		if (*key == '-')
36			use_getopt++;
37		else
38			optind = 2;
39	}
40
41	if (use_getopt)
42		return (getopt(argc, argv, optstring));
43
44	c = *key++;
45	if (c == '\0') {
46		key--;
47		return (-1);
48	}
49	place = strchr(optstring, c);
50
51	if (place == NULL || c == ':') {
52		fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
53		return ('?');
54	}
55
56	place++;
57	if (*place == ':') {
58		if (optind < argc) {
59			optarg = argv[optind];
60			optind++;
61		} else {
62			fprintf(stderr, "%s: %c argument missing\n",
63				argv[0], c);
64			return ('?');
65		}
66	}
67
68	return (c);
69}
70