1/*
2 * Copyright 1993, 1995 Christopher Seiwald.
3 *
4 * This file is part of Jam - see jam.c for Copyright information.
5 */
6
7/*
8 * option.c - command line option processing
9 *
10 * {o >o
11 *  \<>) "Process command line options as defined in <option.h>.
12 *		  Return the number of argv[] elements used up by options,
13 *		  or -1 if an invalid option flag was given or an argument
14 *		  was supplied for an option that does not require one."
15 *
16 * 11/04/02 (seiwald) - const-ing for string literals
17 */
18
19# include "jam.h"
20# include "option.h"
21
22int
23getoptions(
24    int argc,
25    char **argv,
26    const char *opts,
27    option *optv )
28{
29    int i;
30    int optc = N_OPTS;
31
32    memset( (char *)optv, '\0', sizeof( *optv ) * N_OPTS );
33
34    for( i = 0; i < argc; i++ )
35    {
36	char *arg;
37
38	if( argv[i][0] != '-' || !isalpha( argv[i][1] ) )
39	    break;
40
41	if( !optc-- )
42	{
43	    printf( "too many options (%d max)\n", N_OPTS );
44	    return -1;
45	}
46
47	for( arg = &argv[i][1]; *arg; arg++ )
48	{
49	    const char *f;
50
51	    for( f = opts; *f; f++ )
52		if( *f == *arg )
53		    break;
54
55	    if( !*f )
56	    {
57		printf( "Invalid option: -%c\n", *arg );
58		return -1;
59	    }
60
61	    optv->flag = *f;
62
63	    if( f[1] != ':' )
64	    {
65		optv++->val = "true";
66	    }
67	    else if( arg[1] )
68	    {
69		optv++->val = &arg[1];
70		break;
71	    }
72	    else if( ++i < argc )
73	    {
74		optv++->val = argv[i];
75		break;
76	    }
77	    else
78	    {
79		printf( "option: -%c needs argument\n", *f );
80		return -1;
81	    }
82	}
83    }
84
85    return i;
86}
87
88/*
89 * Name: getoptval() - find an option given its character
90 */
91
92const char *
93getoptval(
94	option *optv,
95	char opt,
96	int subopt )
97{
98	int i;
99
100	for( i = 0; i < N_OPTS; i++, optv++ )
101	    if( optv->flag == opt && !subopt-- )
102		return optv->val;
103
104	return 0;
105}
106