/*
Copyright (C) 1998-99 Free Software Foundation, Inc.

Author: Frank Heckenbach <frank@pascal.gnu.de>

Support routines for getopt.pas

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation, version 2.

This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
License for more details.

You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
*/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "getopt.h"

#define EndOfOptions 255

extern int _p_argc;
extern char **_p_argv;

typedef unsigned char Boolean;
typedef unsigned char Char;
typedef enum { NoArgument, RequiredArgument, OptionalArgument } OptArgType;
typedef struct
{
  char       *Name;
  OptArgType  Argument;
  int        *Flag;
  int         V;
} OptionType;

Char _p_getopt (char *OptString);
Char _p_getopt (char *OptString)
{
  int c = getopt (_p_argc, _p_argv, OptString);
  if (c == EOF) c = EndOfOptions;
  return c;
}

Char _p_getopt_long (char *OptString, OptionType *LongOptions,
                     int LongOptionCount, int *PLongIndex, Boolean LongOnly);
Char _p_getopt_long (char *OptString, OptionType *LongOptions,
                     int LongOptionCount, int *PLongIndex, Boolean LongOnly)
{
  int i, c;
  struct option LongOpts [LongOptionCount + 1];
  for (i = 0; i < LongOptionCount; i++)
    {
      int a = LongOptions [i].Argument;
      switch (a)
        {
          case NoArgument       : a = no_argument;       break;
          case RequiredArgument : a = required_argument; break;
          case OptionalArgument : a = optional_argument; break;
        }
      LongOpts [i].has_arg = a;
      LongOpts [i].name = LongOptions [i].Name;
      LongOpts [i].flag = LongOptions [i].Flag;
      LongOpts [i].val  = LongOptions [i].V;
    }
  memset (&LongOpts [LongOptionCount], 0, sizeof (struct option));
  if (LongOnly)
    c = getopt_long_only (_p_argc, _p_argv, OptString, LongOpts, PLongIndex);
  else
    c = getopt_long      (_p_argc, _p_argv, OptString, LongOpts, PLongIndex);
  if (c == EOF) c = EndOfOptions;
  return c;
}
