]> mj.ucw.cz Git - libucw.git/blobdiff - ucw/opt.c
Gary: Symbol renames
[libucw.git] / ucw / opt.c
index 54f8b2b51c811a01cbf067977367ffa1d21a86b6..1a94f7c0bd691042eef5f05d3e279653cd7cea3e 100644 (file)
--- a/ucw/opt.c
+++ b/ucw/opt.c
@@ -1,5 +1,5 @@
 /*
- *     UCW Library -- Parsing of command line options
+ *     UCW Library -- Parsing of command-line options
  *
  *     (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
  *     (c) 2014 Martin Mares <mj@ucw.cz>
 
 #include <ucw/lib.h>
 #include <ucw/opt.h>
-#include <ucw/conf.h>
-#include <ucw/conf-internal.h>
-#include <ucw/fastbuf.h>
+#include <ucw/opt-internal.h>
 #include <ucw/stkstring.h>
 #include <ucw/strtonum.h>
 
 #include <alloca.h>
 #include <math.h>
 
-/***
- * Value flags defaults
- * ~~~~~~~~~~~~~~~~~~~~
- *
- * OPT_NO_VALUE for OPT_BOOL, OPT_SWITCH and OPT_INC
- * OPT_MAYBE_VALUE for OPT_STRING, OPT_UNS, OPT_INT
- * Some of the value flags (OPT_NO_VALUE, OPT_MAYBE_VALUE, OPT_REQUIRED_VALUE)
- * must be specified for OPT_CALL and OPT_USER.
- ***/
 static uns opt_default_value_flags[] = {
     [OPT_CL_BOOL] = OPT_NO_VALUE,
     [OPT_CL_STATIC] = OPT_MAYBE_VALUE,
@@ -39,157 +28,56 @@ static uns opt_default_value_flags[] = {
     [OPT_CL_HELP] = 0
 };
 
-struct opt_precomputed {
-  struct opt_item * item;
-  const char * name;
-  short flags;
-  short count;
-};
-
-struct opt_context {
-  struct opt_precomputed * opts;
-  struct opt_precomputed ** shortopt;
-  struct opt_item ** hooks_before_arg;
-  struct opt_item ** hooks_before_value;
-  struct opt_item ** hooks_after_value;
-  short opt_count;
-  short hooks_before_arg_count;
-  short hooks_before_value_count;
-  short hooks_after_value_count;
-  int positional_max;
-  int positional_count;
-};
-
-static void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
-static void opt_failure(const char * mesg, ...) {
+void opt_failure(const char * mesg, ...) {
   va_list args;
   va_start(args, mesg);
   vfprintf(stderr, mesg, args);
-  fprintf(stderr, "\n");
-  opt_usage();
+  fprintf(stderr, "\nRun with --help for more information.\n");
   exit(OPT_EXIT_BAD_ARGS);
-  va_end(args);                // FIXME: Does this make a sense after exit()?
 }
 
-#define FOREACHLINE(text) for (const char * begin = (text), * end = (text); (*end) && (end = strchrnul(begin, '\n')); begin = end+1)
-
-static inline uns uns_min(uns x, uns y)
+static char *opt_name(struct opt_context *oc, struct opt_precomputed *opt)
 {
-  return MIN(x, y);
+  struct opt_item *item = opt->item;
+  char *res;
+  if (item->letter >= OPT_POSITIONAL_TAIL)
+    res = stk_printf("positional argument #%d", oc->positional_count);
+  else if (opt->flags & OPT_SEEN_AS_LONG)
+    res = stk_printf("--%s", opt->name);
+  else
+    res = stk_printf("-%c", item->letter);
+  return xstrdup(res);
 }
 
-void opt_help(const struct opt_section * help) {
-  int sections_cnt = 0;
-  int lines_cnt = 0;
-
-  for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
-    if (item->flags & OPT_NO_HELP) continue;
-    if (item->cls == OPT_CL_SECTION) {
-      sections_cnt++;
-      continue;
-    }
-    if (!*(item->help)) {
-      lines_cnt++;
-      continue;
-    }
-    FOREACHLINE(item->help)
-      lines_cnt++;
-  }
-
-  struct opt_sectlist {
-    int pos;
-    struct opt_section * sect;
-  } sections[sections_cnt];
-  int s = 0;
-
-  const char *lines[lines_cnt][3];
-  memset(lines, 0, sizeof(lines));
-  int line = 0;
-
-  int linelengths[3] = { -1, -1, -1 };
-
-  for (struct opt_item * item = help->opt; item->cls != OPT_CL_END; item++) {
-    if (item->flags & OPT_NO_HELP) continue;
+#define THIS_OPT opt_name(oc, opt)
 
-    if (item->cls == OPT_CL_HELP) {
-      if (!*(item->help)) {
-       line++;
-       continue;
-      }
-#define SPLITLINES(text) do { \
-      FOREACHLINE(text) { \
-       int cell = 0; \
-       for (const char * b = begin, * e = begin; (e < end) && (e = strchrnul(b, '\t')) && (e > end ? (e = end) : end); b = e+1) { \
-         lines[line][cell] = b; \
-         if (cell >= 2) \
-           break; \
-         else \
-           if (*e == '\t' && linelengths[cell] < (e - b)) \
-             linelengths[cell] = e-b; \
-         cell++; \
-       } \
-       line++; \
-      } } while (0)
-      SPLITLINES(item->help);
-      continue;
-    }
-
-    if (item->cls == OPT_CL_SECTION) {
-      sections[s++] = (struct opt_sectlist) { .pos = line, .sect = item->u.section };
-      continue;
-    }
-
-    uns valoff = strchrnul(item->help, '\t') - item->help;
-    uns eol = strchrnul(item->help, '\n') - item->help;
-    if (valoff > eol)
-      valoff = eol;
-#define VAL(it) ((it->flags & OPT_REQUIRED_VALUE) ? stk_printf("=%.*s", valoff, item->help)  : ((it->flags & OPT_NO_VALUE) ? "" : stk_printf("(=%.*s)", valoff, item->help)))
-    if (item->name) {
-      lines[line][1] = stk_printf("--%s%s", item->name, VAL(item));
-      if (linelengths[1] < (int) strlen(lines[line][1]))
-       linelengths[1] = strlen(lines[line][1]);
-      lines[line][0] = "";
-      if (linelengths[0] < 0)
-       linelengths[0] = 0;
-    }
-    if (item->letter) {
-      lines[line][0] = stk_printf("-%c,", item->letter);
-      if (linelengths[0] < (int) strlen(lines[line][0]))
-       linelengths[0] = strlen(lines[line][0]);
-    }
-#undef VAL
+void opt_precompute(struct opt_precomputed *opt, struct opt_item *item)
+{
+  opt->item = item;
+  opt->count = 0;
+  opt->name = item->name;
+  uns flags = item->flags;
 
-    if (eol > valoff) {
-      lines[line][2] = item->help + valoff + 1;
-    }
+  if (item->letter >= OPT_POSITIONAL_TAIL) {
+    flags &= ~OPT_VALUE_FLAGS;
+    flags |= OPT_REQUIRED_VALUE;
+  }
+  if (!(flags & OPT_VALUE_FLAGS)) {
+    ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
+    flags |= opt_default_value_flags[item->cls];
+  }
 
-    line++;
+  opt->flags = flags;
+}
 
-    if (*(item->help + eol))
-      SPLITLINES(item->help + eol + 1);
-  }
-#undef SPLITLINES
-
-  s = 0;
-#define FIELD(k) linelengths[k], uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
-#define LASTFIELD(k) uns_min(strchrnul(lines[i][k], '\t') - lines[i][k], strchrnul(lines[i][k], '\n') - lines[i][k]), lines[i][k]
-  for (int i=0;i<line;i++) {
-    while (s < sections_cnt && sections[s].pos == i) {
-      opt_help(sections[s].sect);
-      s++;
+static void opt_invoke_hooks(struct opt_context *oc, uns event, struct opt_item *item, char *value)
+{
+  for (int i = 0; i < oc->hook_count; i++) {
+    struct opt_item *hook = oc->hooks[i];
+    if (hook->flags & event) {
+      void *data = (hook->flags & OPT_HOOK_INTERNAL) ? oc : hook->ptr;
+      hook->u.hook(item, event, value, data);
     }
-    if (lines[i][0] == NULL)
-      printf("\n");
-    else if (linelengths[0] == -1 || lines[i][1] == NULL)
-      printf("%.*s\n", LASTFIELD(0));
-    else if (linelengths[1] == -1 || lines[i][2] == NULL)
-      printf("%-*.*s  %.*s\n", FIELD(0), LASTFIELD(1));
-    else
-      printf("%-*.*s  %-*.*s  %.*s\n", FIELD(0), FIELD(1), LASTFIELD(2));
-  }
-  while (s < sections_cnt && sections[s].pos == line) {
-    opt_help(sections[s].sect);
-    s++;
   }
 }
 
@@ -197,59 +85,56 @@ static struct opt_precomputed * opt_find_item_longopt(struct opt_context * oc, c
   uns len = strlen(str);
   struct opt_precomputed * candidate = NULL;
 
-  for (int i=0; i<oc->opt_count; i++) {
-    if (!oc->opts[i].name)
+  for (int i = 0; i < oc->opt_count; i++) {
+    struct opt_precomputed *opt = &oc->opts[i];
+    if (!opt->name)
       continue;
-    if (!strncmp(oc->opts[i].name, str, len)) {
-      if (strlen(oc->opts[i].name) == len) {
-       if (oc->opts[i].count++ && (oc->opts[i].flags & OPT_SINGLE))
-         opt_failure("Option %s appeared the second time.", oc->opts[i].name);
 
-       return &oc->opts[i];
-      }
-      if (candidate)
-       opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i].name);
-      else
-       candidate = &oc->opts[i];
-    }
-    if (!strncmp("no-", str, 3) && !strncmp(oc->opts[i].name, str+3, len-3)) {
-      if (strlen(oc->opts[i].name) == len-3) {
-       if (oc->opts[i].count++ && (oc->opts[i].flags & OPT_SINGLE))
-         opt_failure("Option %s appeared the second time.", oc->opts[i].name);
+    if (!strncmp(opt->name, str, len)) {
+      if (strlen(opt->name) == len)
+       return opt;
+    } else if (opt->item->cls == OPT_CL_BOOL && !strncmp("no-", str, 3) && !strncmp(opt->name, str+3, len-3)) {
+      if (strlen(opt->name) == len-3)
+       return opt;
+    } else
+      continue;
 
-       return &oc->opts[i];
-      }
-      if (candidate)
-       opt_failure("Ambiguous prefix %s: Found matching %s and %s.", str, candidate->name, oc->opts[i].name);
-      else
-       candidate = &oc->opts[i];
-    }
+    if (candidate)
+      opt_failure("Ambiguous option --%s: matches both --%s and --%s.", str, candidate->name, opt->name);
+    else
+      candidate = opt;
   }
 
   if (candidate)
     return candidate;
 
-  opt_failure("Invalid option %s.", str);
+  opt_failure("Invalid option --%s.", str);
 }
 
-#define OPT_PTR(type) ({ \
-  type * ptr; \
-  if (item->flags & OPT_MULTIPLE) { \
-    struct { \
-      cnode n; \
-      type v; \
-    } * n = xmalloc(sizeof(*n)); \
-    clist_add_tail(item->ptr, &(n->n)); \
-    ptr = &(n->v); \
-  } else \
-    ptr = item->ptr; \
+// FIXME: Use simple-lists?
+#define OPT_PTR(type) ({                       \
+  type * ptr;                                  \
+  if (item->flags & OPT_MULTIPLE) {            \
+    struct {                                   \
+      cnode n;                                         \
+      type v;                                  \
+    } * n = xmalloc(sizeof(*n));               \
+    clist_add_tail(item->ptr, &(n->n));        \
+    ptr = &(n->v);                             \
+  } else                                       \
+    ptr = item->ptr;                           \
   ptr; })
 
-#define OPT_NAME (longopt == 2 ? stk_printf("positional arg #%d", oc->positional_count) : (longopt == 1 ? stk_printf("--%s", opt->name) : stk_printf("-%c", item->letter)))
-static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value, int longopt) {
+static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * opt, char * value) {
   struct opt_item * item = opt->item;
-  for (int i=0;i<oc->hooks_before_value_count;i++)
-    oc->hooks_before_value[i]->u.call(item, value, oc->hooks_before_value[i]->ptr);
+
+  if (opt->count++ && (opt->flags & OPT_SINGLE))
+    opt_failure("Option %s must be specified at most once.", THIS_OPT);
+
+  if (opt->flags & OPT_LAST_ARG)
+    oc->stop_parsing = 1;
+
+  opt_invoke_hooks(oc, OPT_HOOK_BEFORE_VALUE, item, value);
 
   switch (item->cls) {
     case OPT_CL_BOOL:
@@ -258,7 +143,7 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
       else if (!strcasecmp(value, "n") || !strcasecmp(value, "no") || !strcasecmp(value, "false") || !strcasecmp(value, "0"))
        *((int *) item->ptr) = 0 ^ (!!(opt->flags & OPT_NEGATIVE));
       else
-       opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): y/n, yes/no, true/false.", OPT_NAME);
+       opt_failure("Boolean argument for %s has a strange value. Supported (case insensitive): 1/0, y/n, yes/no, true/false.", THIS_OPT);
       break;
     case OPT_CL_STATIC:
       {
@@ -270,7 +155,7 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
            else
              e = cf_parse_int(value, OPT_PTR(int));
            if (e)
-             opt_failure("Integer value parsing failed for %s: %s", OPT_NAME, e);
+             opt_failure("Integer value parsing failed for %s: %s", THIS_OPT, e);
            break;
          case CT_U64:
            if (!value)
@@ -278,7 +163,7 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
            else
              e = cf_parse_u64(value, OPT_PTR(u64));
            if (e)
-             opt_failure("Unsigned 64-bit value parsing failed for %s: %s", OPT_NAME, e);
+             opt_failure("Unsigned 64-bit value parsing failed for %s: %s", THIS_OPT, e);
            break;
          case CT_DOUBLE:
            if (!value)
@@ -286,15 +171,15 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
            else
              e = cf_parse_double(value, OPT_PTR(double));
            if (e)
-             opt_failure("Double value parsing failed for %s: %s", OPT_NAME, e);
+             opt_failure("Floating-point value parsing failed for %s: %s", THIS_OPT, e);
            break;
          case CT_IP:
            if (!value)
-             e = cf_parse_ip("0.0.0.0", OPT_PTR(u32));
+             *OPT_PTR(u32) = 0;
            else
              e = cf_parse_ip(value, OPT_PTR(u32));
            if (e)
-             opt_failure("IP parsing failed for %s: %s", OPT_NAME, e);
+             opt_failure("IP address parsing failed for %s: %s", THIS_OPT, e);
            break;
          case CT_STRING:
            if (!value)
@@ -308,8 +193,8 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
        break;
       }
     case OPT_CL_SWITCH:
-      if (*((int *)item->ptr) != -1)
-       opt_failure("Multiple switches: %s", OPT_NAME);
+      if ((opt->flags & OPT_SINGLE) && *((int *)item->ptr) != -1)
+       opt_failure("Multiple switches: %s", THIS_OPT);
       else
        *((int *)item->ptr) = item->u.value;
       break;
@@ -320,24 +205,25 @@ static void opt_parse_value(struct opt_context * oc, struct opt_precomputed * op
        (*((int *)item->ptr))++;
       break;
     case OPT_CL_CALL:
-      item->u.call(item, value, item->ptr);
-      break;
+      {
+       void *data = (opt->flags & OPT_INTERNAL) ? oc : item->ptr;
+       item->u.call(item, value, data);
+       break;
+      }
     case OPT_CL_USER:
       {
        char * e = NULL;
        e = item->u.utype->parser(value, OPT_PTR(void*));
        if (e)
-         opt_failure("User defined type value parsing failed for %s: %s", OPT_NAME, e);
+         opt_failure("Cannot parse the value of %s: %s", THIS_OPT, e);
        break;
       }
     default:
       ASSERT(0);
   }
 
-  for (int i=0;i<oc->hooks_after_value_count;i++)
-    oc->hooks_after_value[i]->u.call(item, value, oc->hooks_after_value[i]->ptr);
+  opt_invoke_hooks(oc, OPT_HOOK_AFTER_VALUE, item, value);
 }
-#undef OPT_NAME
 
 static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
   int eaten = 0;
@@ -346,27 +232,29 @@ static int opt_longopt(struct opt_context * oc, char ** argv, int index) {
   struct opt_precomputed * opt = opt_find_item_longopt(oc, strndupa(name_in, pos));
   char * value = NULL;
 
-  if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3))
+  opt->flags |= OPT_SEEN_AS_LONG;
+
+  if (opt->item->cls == OPT_CL_BOOL && !strncmp(name_in, "no-", 3) && !strncmp(name_in+3, opt->item->name, pos-3)) {
+    if (name_in[pos])
+      opt_failure("Option --%s must not have any value.", name_in);
     value = "n";
-  else if (opt->flags & OPT_REQUIRED_VALUE) {
-    if (pos < strlen(name_in))
+  else if (opt->flags & OPT_REQUIRED_VALUE) {
+    if (name_in[pos])
       value = name_in + pos + 1;
     else {
       value = argv[index+1];
       if (!value)
-       opt_failure("Argument --%s must have a value but nothing supplied.", opt->name);
+       opt_failure("Option %s must have a value, but nothing supplied.", THIS_OPT);
       eaten++;
     }
-  }
-  else if (opt->flags & OPT_MAYBE_VALUE) {
-    if (pos < strlen(name_in))
+  } else if (opt->flags & OPT_MAYBE_VALUE) {
+    if (name_in[pos])
       value = name_in + pos + 1;
+  } else {
+    if (name_in[pos])
+      opt_failure("Option %s must have no value.", THIS_OPT);
   }
-  else {
-    if (pos < strlen(name_in))
-      opt_failure("Argument --%s must not have any value.", opt->name);
-  }
-  opt_parse_value(oc, opt, value, 1);
+  opt_parse_value(oc, opt, value);
   return eaten;
 }
 
@@ -383,30 +271,26 @@ static int opt_shortopt(struct opt_context * oc, char ** argv, int index) {
     if (!opt)
       opt_failure("Unknown option -%c.", o);
 
-    if (opt->count && (opt->flags & OPT_SINGLE))
-      opt_failure("Option -%c must be specified at most once.", o);
-    opt->count++;
+    opt->flags &= ~OPT_SEEN_AS_LONG;
 
     if (opt->flags & OPT_NO_VALUE)
-      opt_parse_value(oc, opt, NULL, 0);
+      opt_parse_value(oc, opt, NULL);
     else if (opt->flags & OPT_REQUIRED_VALUE) {
-      if (chr == 1 && argv[index][2]) {
-        opt_parse_value(oc, opt, argv[index] + 2, 0);
+      if (argv[index][chr+1]) {
+        opt_parse_value(oc, opt, argv[index] + chr + 1);
        return 0;
-      } else if (argv[index][chr+1])
-       opt_failure("Option -%c must have a value, but found inside a bunch of short opts.", o);
-      else if (!argv[index+1])
+      } else if (!argv[index+1])
        opt_failure("Option -%c must have a value, but nothing supplied.", o);
       else {
-       opt_parse_value(oc, opt, argv[index+1], 0);
+       opt_parse_value(oc, opt, argv[index+1]);
        return 1;
       }
     } else if (opt->flags & OPT_MAYBE_VALUE) {
-      if (chr == 1 && argv[index][2]) {
-        opt_parse_value(oc, opt, argv[index] + 2, 0);
+      if (argv[index][chr+1]) {
+        opt_parse_value(oc, opt, argv[index] + chr + 1);
        return 0;
       } else
-       opt_parse_value(oc, opt, NULL, 0);
+       opt_parse_value(oc, opt, NULL);
     } else {
       ASSERT(0);
     }
@@ -419,11 +303,11 @@ static void opt_positional(struct opt_context * oc, char * value) {
   oc->positional_count++;
   uns id = oc->positional_count > oc->positional_max ? OPT_POSITIONAL_TAIL : OPT_POSITIONAL(oc->positional_count);
   struct opt_precomputed * opt = oc->shortopt[id];
-  if (!opt || (opt->flags & OPT_SINGLE) && opt->count)
+  if (!opt)
     opt_failure("Too many positional arguments.");
   else {
-    opt->count++;
-    opt_parse_value(oc, opt, value, 2);
+    opt->flags &= OPT_SEEN_AS_LONG;
+    opt_parse_value(oc, opt, value);
   }
 }
 
@@ -432,16 +316,9 @@ static void opt_count_items(struct opt_context *oc, const struct opt_section *se
   for (const struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
     if (item->cls == OPT_CL_SECTION)
       opt_count_items(oc, item->u.section);
-    else if (item->cls == OPT_CL_HOOK) {
-      if (item->flags & OPT_HOOK_BEFORE_ARG)
-       oc->hooks_before_arg_count++;
-      else if (item->flags & OPT_HOOK_BEFORE_VALUE)
-       oc->hooks_before_value_count++;
-      else if (item->flags & OPT_HOOK_AFTER_VALUE)
-       oc->hooks_after_value_count++;
-      else
-       ASSERT(0);
-    } else if (item->letter || item->name) {
+    else if (item->cls == OPT_CL_HOOK)
+      oc->hook_count++;
+    else if (item->letter || item->name) {
       oc->opt_count++;
       if (item->letter > OPT_POSITIONAL_TAIL)
        oc->positional_max++;
@@ -449,46 +326,18 @@ static void opt_count_items(struct opt_context *oc, const struct opt_section *se
   }
 }
 
-static void opt_add_default_flags(struct opt_precomputed *opt)
-{
-  struct opt_item *item = opt->item;
-  uns flags = opt->flags;
-
-  if (item->letter >= OPT_POSITIONAL_TAIL) {
-    flags &= ~OPT_VALUE_FLAGS;
-    flags |= OPT_REQUIRED_VALUE;
-  }
-  if (!(flags & OPT_VALUE_FLAGS)) {
-    ASSERT(item->cls != OPT_CL_CALL && item->cls != OPT_CL_USER);
-    flags |= opt_default_value_flags[item->cls];
-  }
-
-  opt->flags = flags;
-}
-
 static void opt_prepare_items(struct opt_context *oc, const struct opt_section *sec)
 {
   for (struct opt_item *item = sec->opt; item->cls != OPT_CL_END; item++) {
     if (item->cls == OPT_CL_SECTION)
       opt_prepare_items(oc, item->u.section);
-    else if (item->cls == OPT_CL_HOOK) {
-      if (item->flags & OPT_HOOK_BEFORE_ARG)
-       oc->hooks_before_arg[oc->hooks_before_arg_count++] = item;
-      else if (item->flags & OPT_HOOK_BEFORE_VALUE)
-       oc->hooks_before_value[oc->hooks_before_value_count++] = item;
-      else if (item->flags & OPT_HOOK_AFTER_VALUE)
-       oc->hooks_after_value[oc->hooks_after_value_count++] = item;
-      else
-       ASSERT(0);
-    } else if (item->letter || item->name) {
+    else if (item->cls == OPT_CL_HOOK)
+      oc->hooks[oc->hook_count++] = item;
+    else if (item->letter || item->name) {
       struct opt_precomputed * opt = &oc->opts[oc->opt_count++];
-      opt->item = item;
-      opt->flags = item->flags;
-      opt->count = 0;
-      opt->name = item->name;
+      opt_precompute(opt, item);
       if (item->letter)
        oc->shortopt[(int) item->letter] = opt;
-      opt_add_default_flags(opt);
     }
   }
 }
@@ -500,7 +349,7 @@ static void opt_check_required(struct opt_context *oc)
     if (!opt->count && (opt->flags & OPT_REQUIRED)) {
       struct opt_item *item = opt->item;
       if (item->letter > OPT_POSITIONAL_TAIL)
-       opt_failure("Required positional argument #%d not found.", i - OPT_POSITIONAL_TAIL);
+       opt_failure("Required positional argument #%d not found.", item->letter - OPT_POSITIONAL_TAIL);
       else if (item->letter == OPT_POSITIONAL_TAIL)
        opt_failure("Required positional argument not found.");
       else if (item->letter && item->name)
@@ -513,29 +362,26 @@ static void opt_check_required(struct opt_context *oc)
   }
 }
 
-void opt_parse(const struct opt_section * options, char ** argv) {
+int opt_parse(const struct opt_section * options, char ** argv) {
   struct opt_context * oc = alloca(sizeof(*oc));
   memset(oc, 0, sizeof (*oc));
+  oc->options = options;
 
   opt_count_items(oc, options);
   oc->opts = alloca(sizeof(*oc->opts) * oc->opt_count);
   oc->shortopt = alloca(sizeof(*oc->shortopt) * (oc->positional_max + 257));
   memset(oc->shortopt, 0, sizeof(*oc->shortopt) * (oc->positional_max + 257));
-  oc->hooks_before_arg = alloca(sizeof (*oc->hooks_before_arg) * oc->hooks_before_arg_count);
-  oc->hooks_before_value = alloca(sizeof (*oc->hooks_before_value) * oc->hooks_before_value_count);
-  oc->hooks_after_value = alloca(sizeof (*oc->hooks_after_value) * oc->hooks_after_value_count);
+  oc->hooks = alloca(sizeof (*oc->hooks) * oc->hook_count);
 
   oc->opt_count = 0;
-  oc->hooks_before_arg_count = 0;
-  oc->hooks_before_value_count = 0;
-  oc->hooks_after_value_count = 0;
+  oc->hook_count = 0;
   opt_prepare_items(oc, options);
 
   int force_positional = 0;
-  for (int i = 0; argv[i]; i++) {
+  int i;
+  for (i=0; argv[i] && !oc->stop_parsing; i++) {
     char *arg = argv[i];
-    for (int j = 0; j < oc->hooks_before_arg_count; j++)
-      oc->hooks_before_arg[j]->u.call(NULL, NULL, oc->hooks_before_arg[j]->ptr);
+    opt_invoke_hooks(oc, OPT_HOOK_BEFORE_ARG, NULL, NULL);
     if (arg[0] != '-' || force_positional)
       opt_positional(oc, arg);
     else {
@@ -552,70 +398,6 @@ void opt_parse(const struct opt_section * options, char ** argv) {
   }
 
   opt_check_required(oc);
-}
-
-static void opt_conf_end_of_options(struct cf_context *cc) {
-  cf_load_default(cc);
-  if (cc->postpone_commit && cf_close_group())
-    opt_failure("Loading of configuration failed");
-}
-
-void opt_conf_internal(struct opt_item * opt, const char * value, void * data UNUSED) {
-  struct cf_context *cc = cf_get_context();
-  switch (opt->letter) {
-    case 'S':
-      cf_load_default(cc);
-      if (cf_set(value))
-       opt_failure("Cannot set %s", value);
-      break;
-    case 'C':
-      if (cf_load(value))
-       opt_failure("Cannot load config file %s", value);
-      break;
-#ifdef CONFIG_UCW_DEBUG
-    case '0':
-      opt_conf_end_of_options(cc);
-      struct fastbuf *b = bfdopen(1, 4096);
-      cf_dump_sections(b);
-      bclose(b);
-      exit(0);
-      break;
-#endif
-  }
-}
-
-void opt_conf_hook_internal(struct opt_item * opt, const char * value UNUSED, void * data UNUSED) {
-  static enum {
-    OPT_CONF_HOOK_BEGIN,
-    OPT_CONF_HOOK_CONFIG,
-    OPT_CONF_HOOK_OTHERS
-  } state = OPT_CONF_HOOK_BEGIN;
-
-  int confopt = 0;
-
-  if (opt->letter == 'S' || opt->letter == 'C' || (opt->name && !strcmp(opt->name, "dumpconfig")))
-    confopt = 1;
-
-  switch (state) {
-    case OPT_CONF_HOOK_BEGIN:
-      if (confopt)
-       state = OPT_CONF_HOOK_CONFIG;
-      else {
-       opt_conf_end_of_options(cf_get_context());
-       state = OPT_CONF_HOOK_OTHERS;
-      }
-      break;
-    case OPT_CONF_HOOK_CONFIG:
-      if (!confopt) {
-       opt_conf_end_of_options(cf_get_context());
-       state = OPT_CONF_HOOK_OTHERS;
-      }
-      break;
-    case OPT_CONF_HOOK_OTHERS:
-      if (confopt)
-       opt_failure("Config options (-C, -S) must stand before other options.");
-      break;
-    default:
-      ASSERT(0);
-  }
+  opt_invoke_hooks(oc, OPT_HOOK_FINAL, NULL, NULL);
+  return i;
 }