/*  getopt.cpp
    A simple command line parser.

    28.08.2001 tk, initial implementation, totally unrelated to
               the GNU getopt or similar. (just reinvented the
               wheel, i suppose :)

    Copyright (c)2000 by Thomas Kindler, thomas.kindler@gmx.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. Read the
    full License at http://www.gnu.org/copyleft for more details.
*/

// include files -----
//
#include <string.h>
#include <stdio.h>
#include "getopt.h"


/**
 * Parse command line options
 *
 * \param  argc     argument count, as given to main()
 * \param  argv     array of argument strings
 * \param  options  pointer to options array, the last
 *                  entry must have a NULL-option pointer.
 * \return          number of parsed arguments if successful,
 *                  or 0 if an error occured.
 */
int GetOptions(int argc, char *argv[], CmdOpt *options)
{
  for (int i=1; i<argc; i++) {
    CmdOpt *opt;
    for (opt = options; opt->option; opt++) {
      if (!stricmp(opt->option, argv[i])) {
        if (opt->format) {
          i++;
          if (i >= argc) {
            printf("ERROR   : missing parameter for \"%s\".\n", argv[i-1]);
            return 0;
          }
          if (!sscanf(argv[i], opt->format, opt->param)) {
            printf( "ERROR   : invalid parameter \"%s\" for \"%s\".\n",
                    argv[i], argv[i-1]);
            return 0;
          }
        } else {
          *((bool*)opt->param) = true;
        }
        break;
      }
    }
    if (!opt->option) {
      printf("ERROR   : unkown option \"%s\".\n", argv[i]);
      return 0;
    }
  }
  return argc;
}


/**
 * Print help screen to stdout. The help texts are
 * generated from the options array.
 *
 * \param options  pointer to array of CmdOpt options.
 */
void ShowOptionHelp(CmdOpt *options)
{
  printf(
    "Usage   : extide [option1] [option2] ...\n"
    "Options : "
  );

  while (options->option) {
    printf("%-5s %s\n", options->option, options->help);
    printf("          ");
    options++;
  }
}

