/***************************************************************************
 *   copyright           : (C) 2003 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <config.h>
#include <options.h>
#include <helper.h>
#include <string.h>

#if PARSELIB == 2
#include <popt.h>

char** args_parse (int argc, char** argv,
		   struct args_def* list,
		   void (*arg_fill) (int short_opt,
				     const char* long_opt,
				     char* argument))
{
  int arg;
  poptContext pcon;
  int argcount = 0;
  char** temp;
  char** retval;
  int i = 0;
  struct poptOption* myoptions;
  struct poptOption listEnd = POPT_TABLEEND;

  while(list[i].long_name != NULL ||
	list[i].short_name != 0)
    ++i;
  myoptions = mem_alloc((i+1)*sizeof(*myoptions),0);
  memcpy(&myoptions[i--],&listEnd,sizeof(listEnd));
  for (; i >= 0; --i) {
    myoptions[i].longName = list[i].long_name;
    myoptions[i].shortName = list[i].short_name;
    if (list[i].ptype == ARGS_PARAM_NONE)
      myoptions[i].argInfo = POPT_ARG_NONE;
    else
      myoptions[i].argInfo = POPT_ARG_STRING;
    myoptions[i].arg = NULL;
    myoptions[i].val = i+1;
    myoptions[i].descrip = NULL;
    myoptions[i].argDescrip = NULL;
  }

  pcon = poptGetContext(NULL,argc,(const char **)argv,
			(const struct poptOption*)myoptions,
			POPT_CONTEXT_POSIXMEHARDER);
  while ((arg = poptGetNextOpt(pcon)) > 0) {
    arg_fill(myoptions[arg-1].shortName,myoptions[arg-1].longName,
	     (char*)poptGetOptArg(pcon));
  }
  if (arg < -1) {
    fprintf(stderr, "%s: %s\n",
	    poptBadOption(pcon, POPT_BADOPTION_NOALIAS),
	    poptStrerror(arg));
  }
  
  temp = (char**) poptGetArgs(pcon);
  if (temp != NULL) {
    while (*temp != NULL) {
      ++argcount;
    }
  }
  retval = mem_alloc(argcount+1,0);
  for (i=0; i < argcount;++i) {
    retval[i] = temp[i];
  }
  retval[i]=NULL;

  poptFreeContext(pcon);
  mem_realloc(myoptions,0);
  return retval;
}

#endif
