Merged revisions 310462 via svnmerge from
[asterisk/asterisk.git] / pbx / pbx_config.c
index 1bcb2f5..0baa8e1 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * Asterisk -- An open source telephony toolkit.
  *
- * Copyright (C) 1999 - 2005, Digium, Inc.
+ * Copyright (C) 1999 - 2006, Digium, Inc.
  *
  * Mark Spencer <markster@digium.com>
  *
  * 
  */
 
-#include <sys/types.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <errno.h>
-
 #include "asterisk.h"
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
+#include <ctype.h>
+
+#include "asterisk/paths.h"    /* ast_config_AST_CONFIG_DIR */
 #include "asterisk/pbx.h"
 #include "asterisk/config.h"
-#include "asterisk/options.h"
 #include "asterisk/module.h"
 #include "asterisk/logger.h"
 #include "asterisk/cli.h"
+#include "asterisk/channel.h"  /* AST_MAX_EXTENSION */
 #include "asterisk/callerid.h"
 
-#ifdef __AST_DEBUG_MALLOC
-static void FREE(void *ptr)
-{
-       free(ptr);
-}
-#else
-#define FREE free
-#endif
-
-static char *dtext = "Text Extension Configuration";
-static char *config = "extensions.conf";
-static char *registrar = "pbx_config";
+static const char config[] = "extensions.conf";
+static const char registrar[] = "pbx_config";
+static char userscontext[AST_MAX_EXTENSION] = "default";
 
 static int static_config = 0;
 static int write_protect_config = 1;
-static int autofallthrough_config = 0;
+static int autofallthrough_config = 1;
 static int clearglobalvars_config = 0;
+static int extenpatternmatchnew_config = 0;
+static char *overrideswitch_config = NULL;
 
 AST_MUTEX_DEFINE_STATIC(save_dialplan_lock);
 
 static struct ast_context *local_contexts = NULL;
-
+static struct ast_hashtab *local_table = NULL;
 /*
- * Help for commands provided by this module ...
+ * Prototypes for our completion functions
  */
-static char context_dont_include_help[] =
-"Usage: dont include <context> in <context>\n"
-"       Remove an included context from another context.\n";
-
-static char context_remove_extension_help[] =
-"Usage: remove extension exten@context [priority]\n"
-"       Remove an extension from a given context. If a priority\n"
-"       is given, only that specific priority from the given extension\n"
-"       will be removed.\n";
-
-static char context_add_include_help[] =
-"Usage: include <context> in <context>\n"
-"       Include a context in another context.\n";
-
-static char save_dialplan_help[] =
-"Usage: save dialplan [/path/to/extension/file]\n"
-"       Save dialplan created by pbx_config module.\n"
-"\n"
-"Example: save dialplan                 (/etc/asterisk/extensions.conf)\n"
-"         save dialplan /home/markster  (/home/markster/extensions.conf)\n";
-
-static char context_add_extension_help[] =
-"Usage: add extension <exten>,<priority>,<app>,<app-data> into <context>\n"
-"       [replace]\n\n"
-"       This command will add new extension into <context>. If there is an\n"
-"       existence of extension with the same priority and last 'replace'\n"
-"       arguments is given here we simply replace this extension.\n"
-"\n"
-"Example: add extension 6123,1,Dial,IAX/216.207.245.56/6123 into local\n"
-"         Now, you can dial 6123 and talk to Markster :)\n";
-
-static char context_add_ignorepat_help[] =
-"Usage: add ignorepat <pattern> into <context>\n"
-"       This command adds a new ignore pattern into context <context>\n"
-"\n"
-"Example: add ignorepat _3XX into local\n";
-
-static char context_remove_ignorepat_help[] =
-"Usage: remove ignorepat <pattern> from <context>\n"
-"       This command removes an ignore pattern from context <context>\n"
-"\n"
-"Example: remove ignorepat _3XX from local\n";
-
-static char reload_extensions_help[] =
-"Usage: reload extensions.conf without reloading any other modules\n"
-"       This command does not delete global variables unless\n"
-"       clearglobalvars is set to yes in extensions.conf\n"
-"\n"
-"Example: extensions reload\n";
+static char *complete_dialplan_remove_include(struct ast_cli_args *);
+static char *complete_dialplan_add_include(struct ast_cli_args *);
+static char *complete_dialplan_remove_ignorepat(struct ast_cli_args *);
+static char *complete_dialplan_add_ignorepat(struct ast_cli_args *);
+static char *complete_dialplan_remove_extension(struct ast_cli_args *);
+static char *complete_dialplan_add_extension(struct ast_cli_args *);
 
 /*
  * Implementation of functions provided by this module
@@ -124,241 +70,230 @@ static char reload_extensions_help[] =
 /*!
  * REMOVE INCLUDE command stuff
  */
-static int handle_context_dont_include(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_remove_include(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 5)
-               return RESULT_SHOWUSAGE;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan remove include";
+               e->usage =
+                       "Usage: dialplan remove include <context> from <context>\n"
+                       "       Remove an included context from another context.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_remove_include(a);
+       }
 
-       if (strcmp(argv[3], "in"))
-               return RESULT_SHOWUSAGE;
+       if (strcmp(a->argv[4], "from"))
+               return CLI_SHOWUSAGE;
 
-       if (!ast_context_remove_include(argv[4], argv[2], registrar)) {
-               ast_cli(fd, "We are not including '%s' in '%s' now\n",
-                       argv[2], argv[4]);
-               return RESULT_SUCCESS;
+       if (!ast_context_remove_include(a->argv[5], a->argv[3], registrar)) {
+               ast_cli(a->fd, "We are not including '%s' into '%s' now\n",
+                       a->argv[3], a->argv[5]);
+               return CLI_SUCCESS;
        }
 
-       ast_cli(fd, "Failed to remove '%s' include from '%s' context\n",
-               argv[2], argv[4]);
-       return RESULT_FAILURE;
+       ast_cli(a->fd, "Failed to remove '%s' include from '%s' context\n",
+               a->argv[3], a->argv[5]);
+       return CLI_FAILURE;
 }
 
-static char *complete_context_dont_include(char *line, char *word,
-       int pos, int state)
+/*! \brief return true if 'name' is included by context c */
+static int lookup_ci(struct ast_context *c, const char *name)
 {
-       int which = 0;
+       struct ast_include *i = NULL;
 
-       /*
-        * Context completion ...
-        */
-       if (pos == 2) {
-               struct ast_context *c;
-
-               if (ast_lock_contexts()) {
-                       ast_log(LOG_ERROR, "Failed to lock context list\n");
-                       return NULL;
-               }
+       if (ast_rdlock_context(c))      /* error, skip */
+               return 0;
+       while ( (i = ast_walk_context_includes(c, i)) )
+               if (!strcmp(name, ast_get_include_name(i)))
+                       break;
+       ast_unlock_context(c);
+       return i ? -1 /* success */ : 0;
+}
 
-               /* walk pbx_get_contexts ... */
-               c = ast_walk_contexts(NULL); 
-               while (c) {
-                       struct ast_include *i;
+/*! \brief return true if 'name' is in the ignorepats for context c */
+static int lookup_c_ip(struct ast_context *c, const char *name)
+{
+       struct ast_ignorepat *ip = NULL;
 
-                       if (ast_lock_context(c)) {
-                               c = ast_walk_contexts(c);
-                               continue;
-                       }
+       if (ast_rdlock_context(c))      /* error, skip */
+               return 0;
+       while ( (ip = ast_walk_context_ignorepats(c, ip)) )
+               if (!strcmp(name, ast_get_ignorepat_name(ip)))
+                       break;
+       ast_unlock_context(c);
+       return ip ? -1 /* success */ : 0;
+}
 
-                       i = ast_walk_context_includes(c, NULL);
-                       while (i) {
-                               if (!strlen(word) ||
-                                       !strncmp(ast_get_include_name(i), word, strlen(word))) {
-                                       struct ast_context *nc;
-                                       int already_served = 0;
-
-                                       /* check if this include is already served or not */
-
-                                       /* go through all contexts again till we reach actuall
-                                        * context or already_served = 1
-                                        */
-                                       nc = ast_walk_contexts(NULL);
-                                       while (nc && nc != c && !already_served) {
-                                               if (!ast_lock_context(nc)) {
-                                                       struct ast_include *ni;
-
-                                                       ni = ast_walk_context_includes(nc, NULL);
-                                                       while (ni && !already_served) {
-                                                               if (!strcmp(ast_get_include_name(i),
-                                                                       ast_get_include_name(ni)))
-                                                                       already_served = 1;
-                                                               ni = ast_walk_context_includes(nc, ni);
-                                                       }       
-                                                       
-                                                       ast_unlock_context(nc);
-                                               }
-                                               nc = ast_walk_contexts(nc);
-                                       }
+/*! \brief moves to the n-th word in the string, or empty string if none */
+static const char *skip_words(const char *p, int n)
+{
+       int in_blank = 0;
+       for (;n && *p; p++) {
+               if (isblank(*p) /* XXX order is important */ && !in_blank) {
+                       n--;    /* one word is gone */
+                       in_blank = 1;
+               } else if (/* !is_blank(*p), we know already, && */ in_blank) {
+                       in_blank = 0;
+               }
+       }
+       return p;
+}
 
-                                       if (!already_served) {
-                                               if (++which > state) {
-                                                       char *res =
-                                                               strdup(ast_get_include_name(i));
-                                                       ast_unlock_context(c);
-                                                       ast_unlock_contexts();
-                                                       return res;
-                                               }
-                                       }
-                               }
-                               i = ast_walk_context_includes(c, i);
-                       }
+/*! \brief match the first 'len' chars of word. len==0 always succeeds */
+static int partial_match(const char *s, const char *word, int len)
+{
+       return (len == 0 || !strncmp(s, word, len));
+}
 
-                       ast_unlock_context(c);
-                       c = ast_walk_contexts(c);
+/*! \brief split extension\@context in two parts, return -1 on error.
+ * The return string is malloc'ed and pointed by *ext
+ */
+static int split_ec(const char *src, char **ext, char ** const ctx, char ** const cid)
+{
+       char *i, *c, *e = ast_strdup(src); /* now src is not used anymore */
+
+       if (e == NULL)
+               return -1;      /* malloc error */
+       /* now, parse values from 'exten@context' */
+       *ext = e;
+       c = strchr(e, '@');
+       if (c == NULL)  /* no context part */
+               *ctx = "";      /* it is not overwritten, anyways */
+       else {  /* found context, check for duplicity ... */
+               *c++ = '\0';
+               *ctx = c;
+               if (strchr(c, '@')) { /* two @, not allowed */
+                       free(e);
+                       return -1;
                }
-
-               ast_unlock_contexts();
-               return NULL;
        }
+       if (cid && (i = strchr(e, '/'))) {
+               *i++ = '\0';
+               *cid = i;
+       } else if (cid) {
+               /* Signal none detected */
+               *cid = NULL;
+       }
+       return 0;
+}
 
-       /*
-        * 'in' completion ... (complete only if previous context is really
-        * included somewhere)
-        */
-       if (pos == 3) {
-               struct ast_context *c;
-               char *context, *dupline, *duplinet;
-
-               if (state > 0) return NULL;
+/* _X_ is the string we need to complete */
+static char *complete_dialplan_remove_include(struct ast_cli_args *a)
+{
+       int which = 0;
+       char *res = NULL;
+       int len = strlen(a->word); /* how many bytes to match */
+       struct ast_context *c = NULL;
 
-               /* take 'context' from line ... */
-               if (!(dupline = strdup(line))) {
-                       ast_log(LOG_ERROR, "Out of free memory\n");
+       if (a->pos == 3) {              /* "dialplan remove include _X_" */
+               if (ast_wrlock_contexts()) {
+                       ast_log(LOG_ERROR, "Failed to lock context list\n");
                        return NULL;
                }
+               /* walk contexts and their includes, return the n-th match */
+               while (!res && (c = ast_walk_contexts(c))) {
+                       struct ast_include *i = NULL;
 
-               duplinet = dupline;
-               strsep(&duplinet, " "); /* skip 'dont' */
-               strsep(&duplinet, " "); /* skip 'include' */
-               context = strsep(&duplinet, " ");
+                       if (ast_rdlock_context(c))      /* error ? skip this one */
+                               continue;
 
-               if (!context) {
-                       free(dupline);
-                       return NULL;
-               }
+                       while ( !res && (i = ast_walk_context_includes(c, i)) ) {
+                               const char *i_name = ast_get_include_name(i);
+                               struct ast_context *nc = NULL;
+                               int already_served = 0;
 
-               if (ast_lock_contexts()) {
-                       ast_log(LOG_WARNING, "Failed to lock contexts list\n");
-                       free(dupline);
-                       return NULL;
-               }
+                               if (!partial_match(i_name, a->word, len))
+                                       continue;       /* not matched */
 
-               /* go through all contexts and check if is included ... */
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       struct ast_include *i;
-                       if (ast_lock_context(c)) {
-                               free(dupline);
-                               ast_unlock_contexts();
-                               return NULL;
-                       }
+                               /* check if this include is already served or not */
 
-                       i = ast_walk_context_includes(c, NULL);
-                       while (i) {
-                               /* is it our context? */
-                               if (!strcmp(ast_get_include_name(i), context)) {
-                                       /* yes, it is, context is really included, so
-                                        * complete "in" command
-                                        */
-                                       free(dupline);
-                                       ast_unlock_context(c);
-                                       ast_unlock_contexts();
-                                       return strdup("in");
-                               }
-                               i = ast_walk_context_includes(c, i);
+                               /* go through all contexts again till we reach actual
+                                * context or already_served = 1
+                                */
+                               while ( (nc = ast_walk_contexts(nc)) && nc != c && !already_served)
+                                       already_served = lookup_ci(nc, i_name);
+
+                               if (!already_served && ++which > a->n)
+                                       res = strdup(i_name);
                        }
                        ast_unlock_context(c);
-                       c = ast_walk_contexts(c);
                }
-               free(dupline);
-               ast_unlock_contexts();
-               return NULL;
-       }
 
-       /*
-        * Context from which we removing include ... 
-        */
-       if (pos == 4) {
-               struct ast_context *c;
-               char *context, *dupline, *duplinet, *in;
+               ast_unlock_contexts();
+               return res;
+       } else if (a->pos == 4) { /* "dialplan remove include CTX _X_" */
+               /*
+                * complete as 'from', but only if previous context is really
+                * included somewhere
+                */
+               char *context, *dupline;
+               const char *s = skip_words(a->line, 3); /* skip 'dialplan' 'remove' 'include' */
 
-               if (!(dupline = strdup(line))) {
+               if (a->n > 0)
+                       return NULL;
+               context = dupline = strdup(s);
+               if (!dupline) {
                        ast_log(LOG_ERROR, "Out of free memory\n");
                        return NULL;
                }
+               strsep(&dupline, " ");
 
-               duplinet = dupline;
-
-               strsep(&duplinet, " "); /* skip 'dont' */
-               strsep(&duplinet, " "); /* skip 'include' */
+               if (ast_rdlock_contexts()) {
+                       ast_log(LOG_ERROR, "Failed to lock contexts list\n");
+                       free(context);
+                       return NULL;
+               }
 
-               if (!(context = strsep(&duplinet, " "))) {
-                       free(dupline);
+               /* go through all contexts and check if is included ... */
+               while (!res && (c = ast_walk_contexts(c)))
+                       if (lookup_ci(c, context)) /* context is really included, complete "from" command */
+                               res = strdup("from");
+               ast_unlock_contexts();
+               if (!res)
+                       ast_log(LOG_WARNING, "%s not included anywhere\n", context);
+               free(context);
+               return res;
+       } else if (a->pos == 5) { /* "dialplan remove include CTX from _X_" */
+               /*
+                * Context from which we removing include ... 
+                */
+               char *context, *dupline, *from;
+               const char *s = skip_words(a->line, 3); /* skip 'dialplan' 'remove' 'include' */
+               context = dupline = strdup(s);
+               if (!dupline) {
+                       ast_log(LOG_ERROR, "Out of free memory\n");
                        return NULL;
                }
 
-               /* third word must be in */
-               in = strsep(&duplinet, " ");
-               if (!in ||
-                       strcmp(in, "in")) {
-                       free(dupline);
+               strsep(&dupline, " "); /* skip context */
+
+               /* fourth word must be 'from' */
+               from = strsep(&dupline, " ");
+               if (!from || strcmp(from, "from")) {
+                       free(context);
                        return NULL;
                }
 
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock context list\n");
-                       free(dupline);
+                       free(context);
                        return NULL;
                }
 
                /* walk through all contexts ... */
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       struct ast_include *i;
-                       if (ast_lock_context(c)) {
-                               free(dupline);
-                               return NULL;
-                       }
-       
+               c = NULL;
+               while ( !res && (c = ast_walk_contexts(c))) {
+                       const char *c_name = ast_get_context_name(c);
+                       if (!partial_match(c_name, a->word, len))       /* not a good target */
+                               continue;
                        /* walk through all includes and check if it is our context */  
-                       i = ast_walk_context_includes(c, NULL);
-                       while (i) {
-                               /* is in this context included another on which we want to
-                                * remove?
-                                */
-                               if (!strcmp(context, ast_get_include_name(i))) {
-                                       /* yes, it's included, is matching our word too? */
-                                       if (!strncmp(ast_get_context_name(c),
-                                                       word, strlen(word))) {
-                                               /* check state for completion */
-                                               if (++which > state) {
-                                                       char *res = strdup(ast_get_context_name(c));
-                                                       free(dupline);
-                                                       ast_unlock_context(c);
-                                                       ast_unlock_contexts();
-                                                       return res;
-                                               }
-                                       }
-                                       break;
-                               }
-                               i = ast_walk_context_includes(c, i);
-                       }       
-                       ast_unlock_context(c);
-                       c = ast_walk_contexts(c);
+                       if (lookup_ci(c, context) && ++which > a->n)
+                               res = strdup(c_name);
                }
-
-               free(dupline);
                ast_unlock_contexts();
-               return NULL;
+               free(context);
+               return res;
        }
 
        return NULL;
@@ -367,550 +302,364 @@ static char *complete_context_dont_include(char *line, char *word,
 /*!
  * REMOVE EXTENSION command stuff
  */
-static int handle_context_remove_extension(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_remove_extension(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        int removing_priority = 0;
-       char *exten, *context;
+       char *exten, *context, *cid;
+       char *ret = CLI_FAILURE;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan remove extension";
+               e->usage =
+                       "Usage: dialplan remove extension exten[/cid]@context [priority]\n"
+                       "       Remove an extension from a given context. If a priority\n"
+                       "       is given, only that specific priority from the given extension\n"
+                       "       will be removed.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_remove_extension(a);
+       }
 
-       if (argc != 4 && argc != 3) return RESULT_SHOWUSAGE;
+       if (a->argc != 5 && a->argc != 4)
+               return CLI_SHOWUSAGE;
 
        /*
         * Priority input checking ...
         */
-       if (argc == 4) {
-               char *c = argv[3];
+       if (a->argc == 5) {
+               const char *c = a->argv[4];
 
                /* check for digits in whole parameter for right priority ...
                 * why? because atoi (strtol) returns 0 if any characters in
                 * string and whole extension will be removed, it's not good
                 */
-               if (strcmp("hint", c)) {
-                   while (*c != '\0') {
-                       if (!isdigit(*c++)) {
-                               ast_cli(fd, "Invalid priority '%s'\n", argv[3]);
-                               return RESULT_FAILURE;
+               if (!strcmp("hint", c))
+                       removing_priority = PRIORITY_HINT;
+               else {
+                       while (*c && isdigit(*c))
+                               c++;
+                       if (*c) { /* non-digit in string */
+                               ast_cli(a->fd, "Invalid priority '%s'\n", a->argv[4]);
+                               return CLI_FAILURE;
                        }
-                   }
-                   removing_priority = atoi(argv[3]);
-               } else
-                   removing_priority = PRIORITY_HINT;
+                       removing_priority = atoi(a->argv[4]);
+               }
 
                if (removing_priority == 0) {
-                       ast_cli(fd, "If you want to remove whole extension, please " \
+                       ast_cli(a->fd, "If you want to remove whole extension, please " \
                                "omit priority argument\n");
-                       return RESULT_FAILURE;
+                       return CLI_FAILURE;
                }
        }
 
+       /* XXX original overwrote argv[3] */
        /*
         * Format exten@context checking ...
         */
-       if (!(context = strchr(argv[2], (int)'@'))) {
-               ast_cli(fd, "First argument must be in exten@context format\n");
-               return RESULT_FAILURE;
-       }
-
-       *context++ = '\0';
-       exten = argv[2];
+       if (split_ec(a->argv[3], &exten, &context, &cid))
+               return CLI_FAILURE; /* XXX malloc failure */
        if ((!strlen(exten)) || (!(strlen(context)))) {
-               ast_cli(fd, "Missing extension or context name in second argument '%s@%s'\n",
-                       exten == NULL ? "?" : exten, context == NULL ? "?" : context);
-               return RESULT_FAILURE;
+               ast_cli(a->fd, "Missing extension or context name in third argument '%s'\n",
+                       a->argv[3]);
+               free(exten);
+               return CLI_FAILURE;
        }
 
-       if (!ast_context_remove_extension(context, exten, removing_priority, registrar)) {
+       if (!ast_context_remove_extension_callerid(context, exten, removing_priority,
+                       /* Do NOT substitute S_OR; it is NOT the same thing */
+                       cid ? cid : (removing_priority ? "" : NULL), cid ? 1 : 0, registrar)) {
                if (!removing_priority)
-                       ast_cli(fd, "Whole extension %s@%s removed\n",
+                       ast_cli(a->fd, "Whole extension %s@%s removed\n",
                                exten, context);
                else
-                       ast_cli(fd, "Extension %s@%s with priority %d removed\n",
+                       ast_cli(a->fd, "Extension %s@%s with priority %d removed\n",
                                exten, context, removing_priority);
                        
-               return RESULT_SUCCESS;
-       }
-
-       ast_cli(fd, "Failed to remove extension %s@%s\n", exten, context);
-
-       return RESULT_FAILURE;
-}
-
-#define BROKEN_READLINE 1
-
-#ifdef BROKEN_READLINE
-/*
- * There is one funny thing, when you have word like 300@ and you hit
- * <tab>, you arguments will like as your word is '300 ', so it '@'
- * characters acts sometimes as word delimiter and sometimes as a part
- * of word
- *
- * This fix function, allocates new word variable and store here every
- * time xxx@yyy always as one word and correct pos is set too
- *
- * It's ugly, I know, but I'm waiting for Mark suggestion if upper is
- * bug or feature ...
- */
-static int fix_complete_args(char *line, char **word, int *pos)
-{
-       char *_line, *_strsep_line, *_previous_word = NULL, *_word = NULL;
-       int words = 0;
-
-       _line = strdup(line);
-
-       _strsep_line = _line;
-       while (_strsep_line) {
-               _previous_word = _word;
-               _word = strsep(&_strsep_line, " ");
-
-               if (_word && strlen(_word)) words++;
-       }
-
-
-       if (_word || _previous_word) {
-               if (_word) {
-                       if (!strlen(_word)) words++;
-                       *word = strdup(_word);
-               } else
-                       *word = strdup(_previous_word);
-               *pos = words - 1;
-               free(_line);
-               return 0;
+               ret = CLI_SUCCESS;
+       } else {
+               if (cid) {
+                       ast_cli(a->fd, "Failed to remove extension %s/%s@%s\n", exten, cid, context);
+               } else {
+                       ast_cli(a->fd, "Failed to remove extension %s@%s\n", exten, context);
+               }
+               ret = CLI_FAILURE;
        }
-
-       free(_line);
-       return -1;
+       free(exten);
+       return ret;
 }
-#endif /* BROKEN_READLINE */
 
-static char *complete_context_remove_extension(char *line, char *word, int pos,
-       int state)
+static char *complete_dialplan_remove_extension(struct ast_cli_args *a)
 {
        char *ret = NULL;
        int which = 0;
 
-#ifdef BROKEN_READLINE
-       /*
-        * Fix arguments, *word is a new allocated structure, REMEMBER to
-        * free *word when you want to return from this function ...
-        */
-       if (fix_complete_args(line, &word, &pos)) {
-               ast_log(LOG_ERROR, "Out of free memory\n");
-               return NULL;
-       }
-#endif
+       if (a->pos == 3) { /* 'dialplan remove extension _X_' (exten@context ... */
+               struct ast_context *c = NULL;
+               char *context = NULL, *exten = NULL, *cid = NULL;
+               int le = 0;     /* length of extension */
+               int lc = 0;     /* length of context */
+               int lcid = 0; /* length of cid */
 
-       /*
-        * exten@context completion ... 
-        */
-       if (pos == 2) {
-               struct ast_context *c;
-               struct ast_exten *e;
-               char *context = NULL, *exten = NULL, *delim = NULL;
-
-               /* now, parse values from word = exten@context */
-               if ((delim = strchr(word, (int)'@'))) {
-                       /* check for duplicity ... */
-                       if (delim != strrchr(word, (int)'@')) {
-#ifdef BROKEN_READLINE
-                               free(word);
-#endif
-                               return NULL;
-                       }
-
-                       *delim = '\0';
-                       exten = strdup(word);
-                       context = strdup(delim + 1);
-                       *delim = '@';
-               } else {
-                       exten = strdup(word);
+               lc = split_ec(a->word, &exten, &context, &cid);
+               if (lc) { /* error */
+                       return NULL;
                }
-#ifdef BROKEN_READLINE
-               free(word);
-#endif
+               le = strlen(exten);
+               lc = strlen(context);
+               lcid = cid ? strlen(cid) : -1;
 
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock context list\n");
-                       free(context); free(exten);
-                       return NULL;
+                       goto error2;
                }
 
                /* find our context ... */
-               c = ast_walk_contexts(NULL); 
-               while (c) {
-                       /* our context? */
-                       if ( (!context || !strlen(context)) ||                            /* if no input, all contexts ... */
-                                (context && !strncmp(ast_get_context_name(c),
-                                             context, strlen(context))) ) {                  /* if input, compare ... */
-                               /* try to complete extensions ... */
-                               e = ast_walk_context_extensions(c, NULL);
-                               while (e) {
-                                       /* our extension? */
-                                       if ( (!exten || !strlen(exten)) ||                           /* if not input, all extensions ... */
-                                                (exten && !strncmp(ast_get_extension_name(e), exten,
-                                                                   strlen(exten))) ) { /* if input, compare ... */
-                                               if (++which > state) {
-                                                       /* If there is an extension then return
-                                                        * exten@context.
-                                                        */
-                                                       if (exten) {
-                                                               ret = malloc(strlen(ast_get_extension_name(e)) +
-                                                                       strlen(ast_get_context_name(c)) + 2);
-                                                               if (ret)
-                                                                       sprintf(ret, "%s@%s", ast_get_extension_name(e),
-                                                                               ast_get_context_name(c));
+               while ( (c = ast_walk_contexts(c)) ) {  /* match our context if any */
+                       struct ast_exten *e = NULL;
+                       /* XXX locking ? */
+                       if (!partial_match(ast_get_context_name(c), context, lc))
+                               continue;       /* context not matched */
+                       while ( (e = ast_walk_context_extensions(c, e)) ) { /* try to complete extensions ... */
+                               if ( !strchr(a->word, '/') ||
+                                               (!strchr(a->word, '@') && partial_match(ast_get_extension_cidmatch(e), cid, lcid)) ||
+                                               (strchr(a->word, '@') && !strcmp(ast_get_extension_cidmatch(e), cid))) {
+                                       if ( ((strchr(a->word, '/') || strchr(a->word, '@')) && !strcmp(ast_get_extension_name(e), exten)) ||
+                                                (!strchr(a->word, '/') && !strchr(a->word, '@') && partial_match(ast_get_extension_name(e), exten, le))) { /* n-th match */
+                                               if (++which > a->n) {
+                                                       /* If there is an extension then return exten@context. */
+                                                       if (ast_get_extension_matchcid(e) && (!strchr(a->word, '@') || strchr(a->word, '/'))) {
+                                                               if (asprintf(&ret, "%s/%s@%s", ast_get_extension_name(e), ast_get_extension_cidmatch(e), ast_get_context_name(c)) < 0) {
+                                                                       ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
+                                                                       ret = NULL;
+                                                               }
+                                                               break;
+                                                       } else if (!ast_get_extension_matchcid(e) && !strchr(a->word, '/')) {
+                                                               if (asprintf(&ret, "%s@%s", ast_get_extension_name(e), ast_get_context_name(c)) < 0) {
+                                                                       ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
+                                                                       ret = NULL;
+                                                               }
+                                                               break;
                                                        }
-                                                       free(exten); free(context);
-
-                                                       ast_unlock_contexts();
-       
-                                                       return ret;
                                                }
                                        }
-                                       e = ast_walk_context_extensions(c, e);
                                }
                        }
-                       c = ast_walk_contexts(c);
+                       if (e)  /* got a match */
+                               break;
                }
 
                ast_unlock_contexts();
-
-               free(exten); free(context);
-
-               return NULL;
-       }
-
-       /*
-        * Complete priority ...
-        */
-       if (pos == 3) {
-               char *delim, *exten, *context, *dupline, *duplinet, *ec;
+       error2:
+               free(exten);
+       } else if (a->pos == 4) { /* 'dialplan remove extension EXT _X_' (priority) */
+               char *exten = NULL, *context, *cid, *p;
                struct ast_context *c;
-
-               dupline = strdup(line);
-               if (!dupline) {
-#ifdef BROKEN_READLINE
-                       free(word);
-#endif
-                       return NULL;
-               }
-               duplinet = dupline;
-
-               strsep(&duplinet, " "); /* skip 'remove' */
-               strsep(&duplinet, " "); /* skip 'extension */
-
-               if (!(ec = strsep(&duplinet, " "))) {
-                       free(dupline);
-#ifdef BROKEN_READLINE
-                       free(word);
-#endif
-                       return NULL;
-               }
-
-               /* wrong exten@context format? */
-               if (!(delim = strchr(ec, (int)'@')) ||
-                       (strchr(ec, (int)'@') != strrchr(ec, (int)'@'))) {
-#ifdef BROKEN_READLINE
-                       free(word);
-#endif
-                       free(dupline);
-                       return NULL;
-               }
-
-               /* check if there is exten and context too ... */
-               *delim = '\0';
-               if ((!strlen(ec)) || (!strlen(delim + 1))) {
-#ifdef BROKEN_READLINE
-                       free(word);
-#endif
-                       free(dupline);
-                       return NULL;
-               }
-
-               exten = strdup(ec);
-               context = strdup(delim + 1);
-               free(dupline);
-
-               if (ast_lock_contexts()) {
+               int le, lc, len;
+               const char *s = skip_words(a->line, 3); /* skip 'dialplan' 'remove' 'extension' */
+               int i = split_ec(s, &exten, &context, &cid);    /* parse ext@context */
+
+               if (i)  /* error */
+                       goto error3;
+               if ( (p = strchr(exten, ' ')) ) /* remove space after extension */
+                       *p = '\0';
+               if ( (p = strchr(context, ' ')) ) /* remove space after context */
+                       *p = '\0';
+               le = strlen(exten);
+               lc = strlen(context);
+               len = strlen(a->word);
+               if (le == 0 || lc == 0)
+                       goto error3;
+
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock context list\n");
-#ifdef BROKEN_READLINE
-                       free(word);
-#endif
-                       free(exten); free(context);
-                       return NULL;
+                       goto error3;
                }
 
                /* walk contexts */
-               c = ast_walk_contexts(NULL); 
-               while (c) {
-                       if (!strcmp(ast_get_context_name(c), context)) {
-                               struct ast_exten *e;
-
-                               /* walk extensions */
-                               free(context);
-                               e = ast_walk_context_extensions(c, NULL); 
-                               while (e) {
-                                       if (!strcmp(ast_get_extension_name(e), exten)) {
-                                               struct ast_exten *priority;
-                                               char buffer[10];
-                                       
-                                               free(exten);
-                                               priority = ast_walk_extension_priorities(e, NULL);
-                                               /* serve priorities */
-                                               do {
-                                                       snprintf(buffer, 10, "%u",
-                                                               ast_get_extension_priority(priority));
-                                                       if (!strncmp(word, buffer, strlen(word))) {
-                                                               if (++which > state) {
-#ifdef BROKEN_READLINE
-                                                                       free(word);
-#endif
-                                                                       ast_unlock_contexts();
-                                                                       return strdup(buffer);
-                                                               }
-                                                       }
-                                                       priority = ast_walk_extension_priorities(e,
-                                                               priority);
-                                               } while (priority);
+               c = NULL;
+               while ( (c = ast_walk_contexts(c)) ) {
+                       /* XXX locking on c ? */
+                       struct ast_exten *e;
+                       if (strcmp(ast_get_context_name(c), context) != 0)
+                               continue;
+                       /* got it, we must match here */
+                       e = NULL;
+                       while ( (e = ast_walk_context_extensions(c, e)) ) {
+                               struct ast_exten *priority;
+                               char buffer[10];
 
-#ifdef BROKEN_READLINE
-                                               free(word);
-#endif
-                                               ast_unlock_contexts();
-                                               return NULL;                    
-                                       }
-                                       e = ast_walk_context_extensions(c, e);
+                               if (cid && strcmp(ast_get_extension_cidmatch(e), cid) != 0) {
+                                       continue;
                                }
-#ifdef BROKEN_READLINE
-                               free(word);
-#endif
-                               free(exten);
-                               ast_unlock_contexts();
-                               return NULL;
+                               if (strcmp(ast_get_extension_name(e), exten) != 0)
+                                       continue;
+                               /* XXX lock e ? */
+                               priority = NULL;
+                               while ( !ret && (priority = ast_walk_extension_priorities(e, priority)) ) {
+                                       snprintf(buffer, sizeof(buffer), "%u", ast_get_extension_priority(priority));
+                                       if (partial_match(buffer, a->word, len) && ++which > a->n) /* n-th match */
+                                               ret = strdup(buffer);
+                               }
+                               break;
                        }
-                       c = ast_walk_contexts(c);
+                       break;
                }
-
-#ifdef BROKEN_READLINE
-               free(word);
-#endif
-               free(exten); free(context);
-
                ast_unlock_contexts();
-               return NULL;
+       error3:
+               free(exten);
        }
-
-#ifdef BROKEN_READLINE
-       free(word);
-#endif
-       return NULL; 
+       return ret; 
 }
 
 /*!
  * Include context ...
  */
-static int handle_context_add_include(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_add_include(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 5) return RESULT_SHOWUSAGE;
-
-       /* third arg must be 'in' ... */
-       if (strcmp(argv[3], "in")) return RESULT_SHOWUSAGE;
-
-       if (ast_context_add_include(argv[4], argv[2], registrar)) {
-               switch (errno) {
-                       case ENOMEM:
-                               ast_cli(fd, "Out of memory for context addition\n"); break;
-
-                       case EBUSY:
-                               ast_cli(fd, "Failed to lock context(s) list, please try again later\n"); break;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan add include";
+               e->usage =
+                       "Usage: dialplan add include <context> into <context>\n"
+                       "       Include a context in another context.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_add_include(a);
+       }
 
-                       case EEXIST:
-                               ast_cli(fd, "Context '%s' already included in '%s' context\n",
-                                       argv[1], argv[3]); break;
+       if (a->argc != 6) /* dialplan add include CTX in CTX */
+               return CLI_SHOWUSAGE;
 
-                       case ENOENT:
-                       case EINVAL:
-                               ast_cli(fd, "There is no existence of context '%s'\n",
-                                       errno == ENOENT ? argv[4] : argv[2]); break;
+       /* fifth arg must be 'into' ... */
+       if (strcmp(a->argv[4], "into"))
+               return CLI_SHOWUSAGE;
 
-                       default:
-                               ast_cli(fd, "Failed to include '%s' in '%s' context\n",
-                                       argv[1], argv[3]); break;
+       if (ast_context_add_include(a->argv[5], a->argv[3], registrar)) {
+               switch (errno) {
+               case ENOMEM:
+                       ast_cli(a->fd, "Out of memory for context addition\n");
+                       break;
+
+               case EBUSY:
+                       ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
+                       break;
+
+               case EEXIST:
+                       ast_cli(a->fd, "Context '%s' already included in '%s' context\n",
+                               a->argv[3], a->argv[5]);
+                       break;
+
+               case ENOENT:
+               case EINVAL:
+                       ast_cli(a->fd, "There is no existence of context '%s'\n",
+                               errno == ENOENT ? a->argv[5] : a->argv[3]);
+                       break;
+
+               default:
+                       ast_cli(a->fd, "Failed to include '%s' in '%s' context\n",
+                               a->argv[3], a->argv[5]);
+                       break;
                }
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
        /* show some info ... */
-       ast_cli(fd, "Context '%s' included in '%s' context\n",
-               argv[2], argv[3]);
+       ast_cli(a->fd, "Context '%s' included in '%s' context\n",
+               a->argv[3], a->argv[5]);
 
-       return RESULT_SUCCESS;
+       return CLI_SUCCESS;
 }
 
-static char *complete_context_add_include(char *line, char *word, int pos,
-    int state)
+static char *complete_dialplan_add_include(struct ast_cli_args *a)
 {
        struct ast_context *c;
        int which = 0;
+       char *ret = NULL;
+       int len = strlen(a->word);
 
-       /* server context for inclusion ... */
-       if (pos == 1)
-       {
-               if (ast_lock_contexts()) {
+       if (a->pos == 3) {              /* 'dialplan add include _X_' (context) ... */
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock context list\n");
                        return NULL;
                }
-
-               /* server all contexts */ 
-               c = ast_walk_contexts(NULL); 
-               while (c) {
-                       if ((!strlen(word) || 
-                                !strncmp(ast_get_context_name(c), word, strlen(word))) &&
-                               ++which > state)
-                       {
-                               char *context = strdup(ast_get_context_name(c));
-                               ast_unlock_contexts();
-                               return context;
-                       }
-                       c = ast_walk_contexts(c);
-               }
-
+               for (c = NULL; !ret && (c = ast_walk_contexts(c)); )
+                       if (partial_match(ast_get_context_name(c), a->word, len) && ++which > a->n)
+                               ret = strdup(ast_get_context_name(c));
                ast_unlock_contexts();
-       }
+               return ret;
+       } else if (a->pos == 4) { /* dialplan add include CTX _X_ */
+               /* complete  as 'into' if context exists or we are unable to check */
+               char *context, *dupline;
+               const char *s = skip_words(a->line, 3); /* should not fail */
 
-       /* complete 'in' only if context exist ... */
-       if (pos == 2)
-       {
-               char *context, *dupline, *duplinet;
-
-               if (state != 0) return NULL;
+               if (a->n != 0)  /* only once */
+                       return NULL;
 
                /* parse context from line ... */
-               if (!(dupline = strdup(line))) {
+               context = dupline = strdup(s);
+               if (!context) {
                        ast_log(LOG_ERROR, "Out of free memory\n");
-                       if (state == 0) return strdup("in");
-                       return NULL;
+                       return strdup("into");
                }
+               strsep(&dupline, " ");
 
-               duplinet = dupline;
-
-               strsep(&duplinet, " ");
-               context = strsep(&duplinet, " ");
-               if (context) {
-                       struct ast_context *c;
-                       int context_existence = 0;
-
-                       /* check for context existence ... */
-                       if (ast_lock_contexts()) {
-                               ast_log(LOG_ERROR, "Failed to lock context list\n");
-                               free(dupline);
-                               /* our fault, we can't check, so complete 'in' ... */
-                               return strdup("in");
-                       }
-
-                       c = ast_walk_contexts(NULL);
-                       while (c && !context_existence) {
-                               if (!strcmp(context, ast_get_context_name(c))) {
-                                       context_existence = 1;
-                                       continue;
-                               }
-                               c = ast_walk_contexts(c);
-                       }
-
-                       /* if context exists, return 'into' ... */
-                       if (context_existence) {
-                               free(dupline);
-                               ast_unlock_contexts();
-                               return strdup("into");
-                       }
-
+               /* check for context existence ... */
+               if (ast_rdlock_contexts()) {
+                       ast_log(LOG_ERROR, "Failed to lock context list\n");
+                       /* our fault, we can't check, so complete 'into' ... */
+                       ret = strdup("into");
+               } else {
+                       struct ast_context *ctx;
+                       for (ctx = NULL; !ret && (ctx = ast_walk_contexts(ctx)); )
+                               if (!strcmp(context, ast_get_context_name(ctx)))
+                                       ret = strdup("into"); /* found */
                        ast_unlock_contexts();
-               }       
-
-               free(dupline);
-               return NULL;
-       }
-
-       /* serve context into which we include another context */
-       if (pos == 3)
-       {
-               char *context, *dupline, *duplinet, *in;
-               int context_existence = 0;
-
-               if (!(dupline = strdup(line))) {
+               }
+               free(context);
+               return ret;
+       } else if (a->pos == 5) { /* 'dialplan add include CTX into _X_' (dst context) */
+               char *context, *dupline, *into;
+               const char *s = skip_words(a->line, 3); /* should not fail */
+               context = dupline = strdup(s);
+               if (!dupline) {
                        ast_log(LOG_ERROR, "Out of free memory\n");
                        return NULL;
                }
-
-               duplinet = dupline;
-
-               strsep(&duplinet, " "); /* skip 'include' */
-               context = strsep(&duplinet, " ");
-               in = strsep(&duplinet, " ");
-
-               /* given some context and third word is in? */
-               if (!strlen(context) || strcmp(in, "in")) {
-                       free(dupline);
-                       return NULL;
+               strsep(&dupline, " "); /* skip context */
+               into = strsep(&dupline, " ");
+               /* error if missing context or fifth word is not 'into' */
+               if (!strlen(context) || strcmp(into, "into")) {
+                       ast_log(LOG_ERROR, "bad context %s or missing into %s\n",
+                               context, into);
+                       goto error3;
                }
 
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock context list\n");
-                       free(dupline);
-                       return NULL;
-               }
-
-               /* check for context existence ... */
-               c = ast_walk_contexts(NULL);
-               while (c && !context_existence) {
-                       if (!strcmp(context, ast_get_context_name(c))) {
-                               context_existence = 1;
-                               continue;
-                       }
-                       c = ast_walk_contexts(c);
-               }
-
-               if (!context_existence) {
-                       free(dupline);
-                       ast_unlock_contexts();
-                       return NULL;
+                       goto error3;
                }
 
-               /* go through all contexts ... */
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       /* must be different contexts ... */
-                       if (strcmp(context, ast_get_context_name(c))) {
-                               if (!ast_lock_context(c)) {
-                                       struct ast_include *i;
-                                       int included = 0;
-
-                                       /* check for duplicity inclusion ... */
-                                       i = ast_walk_context_includes(c, NULL);
-                                       while (i && !included) {
-                                               if (!strcmp(ast_get_include_name(i), context))
-                                                       included = 1;
-                                               i = ast_walk_context_includes(c, i);
-                                       }
-                                       ast_unlock_context(c);
-
-                                       /* not included yet, so show possibility ... */
-                                       if (!included &&
-                                               !strncmp(ast_get_context_name(c), word, strlen(word))){
-                                               
-                                               if (++which > state) {
-                                                       char *res = strdup(ast_get_context_name(c));
-                                                       free(dupline);
-                                                       ast_unlock_contexts();
-                                                       return res;
-                                               }
-                                       }       
-                               }
+               for (c = NULL; (c = ast_walk_contexts(c)); )
+                       if (!strcmp(context, ast_get_context_name(c)))
+                               break;
+               if (c) { /* first context exists, go on... */
+                       /* go through all contexts ... */
+                       for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
+                               if (!strcmp(context, ast_get_context_name(c)))
+                                       continue; /* skip ourselves */
+                               if (partial_match(ast_get_context_name(c), a->word, len) &&
+                                               !lookup_ci(c, context) /* not included yet */ &&
+                                               ++which > a->n)
+                                       ret = strdup(ast_get_context_name(c));
                        }
-                       c = ast_walk_contexts(c);
+               } else {
+                       ast_log(LOG_ERROR, "context %s not found\n", context);
                }
-
                ast_unlock_contexts();
-               free(dupline);
-               return NULL;
+       error3:
+               free(context);
+               return ret;
        }
 
        return NULL;
@@ -919,75 +668,98 @@ static char *complete_context_add_include(char *line, char *word, int pos,
 /*!
  * \brief 'save dialplan' CLI command implementation functions ...
  */
-static int handle_save_dialplan(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_save(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       char filename[256];
+       char filename[256], overrideswitch[256] = "";
        struct ast_context *c;
        struct ast_config *cfg;
        struct ast_variable *v;
-       int context_header_written;
        int incomplete = 0; /* incomplete config write? */
        FILE *output;
+       struct ast_flags config_flags = { 0 };
+       const char *base, *slash, *file;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan save";
+               e->usage =
+                       "Usage: dialplan save [/path/to/extension/file]\n"
+                       "       Save dialplan created by pbx_config module.\n"
+                       "\n"
+                       "Example: dialplan save                 (/etc/asterisk/extensions.conf)\n"
+                       "         dialplan save /home/markster  (/home/markster/extensions.conf)\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
 
        if (! (static_config && !write_protect_config)) {
-               ast_cli(fd,
+               ast_cli(a->fd,
                        "I can't save dialplan now, see '%s' example file.\n",
                        config);
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
-       if (argc != 2 && argc != 3) return RESULT_SHOWUSAGE;
+       if (a->argc != 2 && a->argc != 3)
+               return CLI_SHOWUSAGE;
 
        if (ast_mutex_lock(&save_dialplan_lock)) {
-               ast_cli(fd,
+               ast_cli(a->fd,
                        "Failed to lock dialplan saving (another proccess saving?)\n");
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
-
-       /* have config path? */
-       if (argc == 3) {
-               /* is there extension.conf too? */
-               if (!strstr(argv[2], ".conf")) {
-                       /* no, only directory path, check for last '/' occurence */
-                       if (*(argv[2] + strlen(argv[2]) -1) == '/')
-                               snprintf(filename, sizeof(filename), "%s%s",
-                                       argv[2], config);
-                       else
-                               /* without config extensions.conf, add it */
-                               snprintf(filename, sizeof(filename), "%s/%s",
-                                       argv[2], config);
-               } else
-                       /* there is an .conf */
-                       snprintf(filename, sizeof(filename), argv[2]);
-       } else
+       /* XXX the code here is quite loose, a pathname with .conf in it
+        * is assumed to be a complete pathname
+        */
+       if (a->argc == 3) {     /* have config path. Look for *.conf */
+               base = a->argv[2];
+               if (!strstr(a->argv[2], ".conf")) { /*no, this is assumed to be a pathname */
+                       /* if filename ends with '/', do not add one */
+                       slash = (*(a->argv[2] + strlen(a->argv[2]) -1) == '/') ? "/" : "";
+                       file = config;  /* default: 'extensions.conf' */
+               } else {        /* yes, complete file name */
+                       slash = "";
+                       file = "";
+               }
+       } else {
                /* no config file, default one */
-               snprintf(filename, sizeof(filename), "%s/%s",
-                       (char *)ast_config_AST_CONFIG_DIR, config);
+               base = ast_config_AST_CONFIG_DIR;
+               slash = "/";
+               file = config;
+       }
+       snprintf(filename, sizeof(filename), "%s%s%s", base, slash, config);
 
-       cfg = ast_config_load("extensions.conf");
+       cfg = ast_config_load("extensions.conf", config_flags);
 
        /* try to lock contexts list */
-       if (ast_lock_contexts()) {
-               ast_cli(fd, "Failed to lock contexts list\n");
+       if (ast_rdlock_contexts()) {
+               ast_cli(a->fd, "Failed to lock contexts list\n");
                ast_mutex_unlock(&save_dialplan_lock);
                ast_config_destroy(cfg);
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
        /* create new file ... */
        if (!(output = fopen(filename, "wt"))) {
-               ast_cli(fd, "Failed to create file '%s'\n",
+               ast_cli(a->fd, "Failed to create file '%s'\n",
                        filename);
                ast_unlock_contexts();
                ast_mutex_unlock(&save_dialplan_lock);
                ast_config_destroy(cfg);
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
        /* fireout general info */
-       fprintf(output, "[general]\nstatic=%s\nwriteprotect=%s\n\n",
+       if (overrideswitch_config) {
+               snprintf(overrideswitch, sizeof(overrideswitch), "overrideswitch=%s\n", overrideswitch_config);
+       }
+       fprintf(output, "[general]\nstatic=%s\nwriteprotect=%s\nautofallthrough=%s\nclearglobalvars=%s\n%sextenpatternmatchnew=%s\n\n",
                static_config ? "yes" : "no",
-               write_protect_config ? "yes" : "no");
+               write_protect_config ? "yes" : "no",
+                autofallthrough_config ? "yes" : "no",
+                               clearglobalvars_config ? "yes" : "no",
+                               overrideswitch_config ? overrideswitch : "",
+                               extenpatternmatchnew_config ? "yes" : "no");
 
        if ((v = ast_variable_browse(cfg, "globals"))) {
                fprintf(output, "[globals]\n");
@@ -1000,144 +772,113 @@ static int handle_save_dialplan(int fd, int argc, char *argv[])
 
        ast_config_destroy(cfg);
        
+#define PUT_CTX_HDR    do { \
+       if (!context_header_written) {  \
+               fprintf(output, "[%s]\n", ast_get_context_name(c));     \
+               context_header_written = 1;     \
+       }       \
+       } while (0)
+
        /* walk all contexts */
-       c = ast_walk_contexts(NULL);
-       while (c) {
-               context_header_written = 0;
-       
-               /* try to lock context and fireout all info */  
-               if (!ast_lock_context(c)) {
-                       struct ast_exten *e, *last_written_e = NULL;
-                       struct ast_include *i;
-                       struct ast_ignorepat *ip;
-                       struct ast_sw *sw;
+       for (c = NULL; (c = ast_walk_contexts(c)); ) {
+               int context_header_written = 0;
+               struct ast_exten *ext, *last_written_e = NULL;
+               struct ast_include *i;
+               struct ast_ignorepat *ip;
+               struct ast_sw *sw;
 
-                       /* registered by this module? */
-                       if (!strcmp(ast_get_context_registrar(c), registrar)) {
-                               fprintf(output, "[%s]\n", ast_get_context_name(c));
-                               context_header_written = 1;
-                       }
+               /* try to lock context and fireout all info */  
+               if (ast_rdlock_context(c)) { /* lock failure */
+                       incomplete = 1;
+                       continue;
+               }
+               /* registered by this module? */
+               /* XXX do we need this ? */
+               if (!strcmp(ast_get_context_registrar(c), registrar)) {
+                       fprintf(output, "[%s]\n", ast_get_context_name(c));
+                       context_header_written = 1;
+               }
 
-                       /* walk extensions ... */
-                       e = ast_walk_context_extensions(c, NULL);
-                       while (e) {
-                               struct ast_exten *p;
+               /* walk extensions ... */
+               for (ext = NULL; (ext = ast_walk_context_extensions(c, ext)); ) {
+                       struct ast_exten *p = NULL;
 
-                               /* fireout priorities */
-                               p = ast_walk_extension_priorities(e, NULL);
-                               while (p) {
-                                       if (!strcmp(ast_get_extension_registrar(p),
-                                               registrar)) {
+                       /* fireout priorities */
+                       while ( (p = ast_walk_extension_priorities(ext, p)) ) {
+                               if (strcmp(ast_get_extension_registrar(p), registrar) != 0) /* not this source */
+                                       continue;
+               
+                               /* make empty line between different extensions */      
+                               if (last_written_e != NULL &&
+                                           strcmp(ast_get_extension_name(last_written_e),
+                                                   ast_get_extension_name(p)))
+                                       fprintf(output, "\n");
+                               last_written_e = p;
                        
-                                               /* make empty line between different extensions */      
-                                               if (last_written_e != NULL &&
-                                                       strcmp(ast_get_extension_name(last_written_e),
-                                                               ast_get_extension_name(p)))
-                                                       fprintf(output, "\n");
-                                               last_written_e = p;
+                               PUT_CTX_HDR;
+
+                               if (ast_get_extension_priority(p) == PRIORITY_HINT) { /* easy */
+                                       fprintf(output, "exten => %s,hint,%s\n",
+                                                   ast_get_extension_name(p),
+                                                   ast_get_extension_app(p));
+                               } else {
+                                       const char *sep, *cid;
+                                       const char *el = ast_get_extension_label(p);
+                                       char label[128] = "";
+                                       if (ast_get_extension_matchcid(p)) {
+                                               sep = "/";
+                                               cid = ast_get_extension_cidmatch(p);
+                                       } else
+                                               sep = cid = "";
                                
-                                               if (!context_header_written) {
-                                                       fprintf(output, "[%s]\n", ast_get_context_name(c));
-                                                       context_header_written = 1;
-                                               }
-
-                                               if (ast_get_extension_priority(p)!=PRIORITY_HINT) {
-                                                       char *tempdata = NULL, *startdata;
-                                                       tempdata = strdup((char *)ast_get_extension_app_data(p));
-                                                       if (tempdata) {
-                                                               startdata = tempdata;
-                                                               while (*tempdata) {
-                                                                       if (*tempdata == '|')
-                                                                               *tempdata = ',';
-                                                                       tempdata++;
-                                                               }
-                                                               tempdata = startdata;
-                                                       }
-                                                       if (ast_get_extension_matchcid(p))
-                                                               fprintf(output, "exten => %s/%s,%d,%s(%s)\n",
-                                                                   ast_get_extension_name(p),
-                                                                   ast_get_extension_cidmatch(p),
-                                                                   ast_get_extension_priority(p),
-                                                                   ast_get_extension_app(p),
-                                                                   tempdata);
-                                                       else
-                                                               fprintf(output, "exten => %s,%d,%s(%s)\n",
-                                                                   ast_get_extension_name(p),
-                                                                   ast_get_extension_priority(p),
-                                                                   ast_get_extension_app(p),
-                                                                   tempdata);
-                                                       if (tempdata)
-                                                               free(tempdata);
-                                               } else
-                                                       fprintf(output, "exten => %s,hint,%s\n",
-                                                           ast_get_extension_name(p),
-                                                           ast_get_extension_app(p));
-                                               
-                                       }
-                                       p = ast_walk_extension_priorities(e, p);
-                               }
-
-                               e = ast_walk_context_extensions(c, e);
-                       }
-
-                       /* written any extensions? ok, write space between exten & inc */
-                       if (last_written_e) fprintf(output, "\n");
-
-                       /* walk through includes */
-                       i = ast_walk_context_includes(c, NULL);
-                       while (i) {
-                               if (!strcmp(ast_get_include_registrar(i), registrar)) {
-                                       if (!context_header_written) {
-                                               fprintf(output, "[%s]\n", ast_get_context_name(c));
-                                               context_header_written = 1;
-                                       }
-                                       fprintf(output, "include => %s\n",
-                                               ast_get_include_name(i));
+                                       if (el && (snprintf(label, sizeof(label), "(%s)", el) != (strlen(el) + 2)))
+                                               incomplete = 1; /* error encountered or label > 125 chars */
+                                       
+                                       fprintf(output, "exten => %s%s%s,%d%s,%s(%s)\n",
+                                           ast_get_extension_name(p), (ast_strlen_zero(sep) ? "" : sep), (ast_strlen_zero(cid) ? "" : cid),
+                                           ast_get_extension_priority(p), label,
+                                           ast_get_extension_app(p), (ast_strlen_zero(ast_get_extension_app_data(p)) ? "" : (const char *)ast_get_extension_app_data(p)));
                                }
-                               i = ast_walk_context_includes(c, i);
                        }
+               }
 
-                       if (ast_walk_context_includes(c, NULL))
-                               fprintf(output, "\n");
-
-                       /* walk through switches */
-                       sw = ast_walk_context_switches(c, NULL);
-                       while (sw) {
-                               if (!strcmp(ast_get_switch_registrar(sw), registrar)) {
-                                       if (!context_header_written) {
-                                               fprintf(output, "[%s]\n", ast_get_context_name(c));
-                                               context_header_written = 1;
-                                       }
-                                       fprintf(output, "switch => %s/%s\n",
-                                               ast_get_switch_name(sw),
-                                               ast_get_switch_data(sw));
-                               }
-                               sw = ast_walk_context_switches(c, sw);
-                       }
+               /* written any extensions? ok, write space between exten & inc */
+               if (last_written_e)
+                       fprintf(output, "\n");
 
-                       if (ast_walk_context_switches(c, NULL))
-                               fprintf(output, "\n");
+               /* walk through includes */
+               for (i = NULL; (i = ast_walk_context_includes(c, i)) ; ) {
+                       if (strcmp(ast_get_include_registrar(i), registrar) != 0)
+                               continue; /* not mine */
+                       PUT_CTX_HDR;
+                       fprintf(output, "include => %s\n", ast_get_include_name(i));
+               }
+               if (ast_walk_context_includes(c, NULL))
+                       fprintf(output, "\n");
+
+               /* walk through switches */
+               for (sw = NULL; (sw = ast_walk_context_switches(c, sw)) ; ) {
+                       if (strcmp(ast_get_switch_registrar(sw), registrar) != 0)
+                               continue; /* not mine */
+                       PUT_CTX_HDR;
+                       fprintf(output, "switch => %s/%s\n",
+                                   ast_get_switch_name(sw), ast_get_switch_data(sw));
+               }
 
-                       /* fireout ignorepats ... */
-                       ip = ast_walk_context_ignorepats(c, NULL);
-                       while (ip) {
-                               if (!strcmp(ast_get_ignorepat_registrar(ip), registrar)) {
-                                       if (!context_header_written) {
-                                               fprintf(output, "[%s]\n", ast_get_context_name(c));
-                                               context_header_written = 1;
-                                       }
+               if (ast_walk_context_switches(c, NULL))
+                       fprintf(output, "\n");
 
-                                       fprintf(output, "ignorepat => %s\n",
+               /* fireout ignorepats ... */
+               for (ip = NULL; (ip = ast_walk_context_ignorepats(c, ip)); ) {
+                       if (strcmp(ast_get_ignorepat_registrar(ip), registrar) != 0)
+                               continue; /* not mine */
+                       PUT_CTX_HDR;
+                       fprintf(output, "ignorepat => %s\n",
                                                ast_get_ignorepat_name(ip));
-                               }
-                               ip = ast_walk_context_ignorepats(c, ip);
-                       }
-
-                       ast_unlock_context(c);
-               } else
-                       incomplete = 1;
+               }
 
-               c = ast_walk_contexts(c);
+               ast_unlock_context(c);
        }       
 
        ast_unlock_contexts();
@@ -1145,19 +886,19 @@ static int handle_save_dialplan(int fd, int argc, char *argv[])
        fclose(output);
 
        if (incomplete) {
-               ast_cli(fd, "Saved dialplan is incomplete\n");
-               return RESULT_FAILURE;
+               ast_cli(a->fd, "Saved dialplan is incomplete\n");
+               return CLI_FAILURE;
        }
 
-       ast_cli(fd, "Dialplan successfully saved into '%s'\n",
+       ast_cli(a->fd, "Dialplan successfully saved into '%s'\n",
                filename);
-       return RESULT_SUCCESS;
+       return CLI_SUCCESS;
 }
 
 /*!
  * \brief ADD EXTENSION command stuff
  */
-static int handle_context_add_extension(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_add_extension(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        char *whole_exten;
        char *exten, *prior;
@@ -1165,26 +906,47 @@ static int handle_context_add_extension(int fd, int argc, char *argv[])
        char *cidmatch, *app, *app_data;
        char *start, *end;
 
-       /* check for arguments at first */
-       if (argc != 5 && argc != 6) return RESULT_SHOWUSAGE;
-       if (strcmp(argv[3], "into")) return RESULT_SHOWUSAGE;
-       if (argc == 6) if (strcmp(argv[5], "replace")) return RESULT_SHOWUSAGE;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan add extension";
+               e->usage =
+                       "Usage: dialplan add extension <exten>,<priority>,<app>,<app-data>\n"
+                       "       into <context> [replace]\n\n"
+                       "       This command will add new extension into <context>. If there is an\n"
+                       "       existence of extension with the same priority and last 'replace'\n"
+                       "       arguments is given here we simply replace this extension.\n"
+                       "\n"
+                       "Example: dialplan add extension 6123,1,Dial,IAX/216.207.245.56/6123 into local\n"
+                       "         Now, you can dial 6123 and talk to Markster :)\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_add_extension(a);
+       }
 
-       whole_exten = argv[2];
-       exten           = strsep(&whole_exten,",");
+       /* check for arguments at first */
+       if (a->argc != 6 && a->argc != 7)
+               return CLI_SHOWUSAGE;
+       if (strcmp(a->argv[4], "into"))
+               return CLI_SHOWUSAGE;
+       if (a->argc == 7)
+               if (strcmp(a->argv[6], "replace"))
+                       return CLI_SHOWUSAGE;
+
+       whole_exten = ast_strdupa(a->argv[3]);
+       exten = strsep(&whole_exten,",");
        if (strchr(exten, '/')) {
                cidmatch = exten;
                strsep(&cidmatch,"/");
        } else {
                cidmatch = NULL;
        }
-       prior       = strsep(&whole_exten,",");
+       prior = strsep(&whole_exten,",");
        if (prior) {
-       if (!strcmp(prior, "hint")) {
+               if (!strcmp(prior, "hint")) {
                        iprior = PRIORITY_HINT;
                } else {
-                       if (sscanf(prior, "%d", &iprior) != 1) {
-                               ast_cli(fd, "'%s' is not a valid priority\n", prior);
+                       if (sscanf(prior, "%30d", &iprior) != 1) {
+                               ast_cli(a->fd, "'%s' is not a valid priority\n", prior);
                                prior = NULL;
                        }
                }
@@ -1193,7 +955,6 @@ static int handle_context_add_extension(int fd, int argc, char *argv[])
        if (app && (start = strchr(app, '(')) && (end = strrchr(app, ')'))) {
                *start = *end = '\0';
                app_data = start + 1;
-               ast_process_quotes_and_slashes(app_data, ',', '|');
        } else {
                if (app) {
                        app_data = strchr(app, ',');
@@ -1205,292 +966,275 @@ static int handle_context_add_extension(int fd, int argc, char *argv[])
                        app_data = NULL;
        }
 
-       if (!exten || !prior || !app || (!app_data && iprior != PRIORITY_HINT)) return RESULT_SHOWUSAGE;
+       if (!exten || !prior || !app || (!app_data && iprior != PRIORITY_HINT))
+               return CLI_SHOWUSAGE;
 
        if (!app_data)
                app_data="";
-       if (ast_add_extension(argv[4], argc == 6 ? 1 : 0, exten, iprior, NULL, cidmatch, app,
-               (void *)strdup(app_data), free, registrar)) {
+       if (ast_add_extension(a->argv[5], a->argc == 7 ? 1 : 0, exten, iprior, NULL, cidmatch, app,
+               (void *)strdup(app_data), ast_free_ptr, registrar)) {
                switch (errno) {
-                       case ENOMEM:
-                               ast_cli(fd, "Out of free memory\n"); break;
-
-                       case EBUSY:
-                               ast_cli(fd, "Failed to lock context(s) list, please try again later\n"); break;
-
-                       case ENOENT:
-                               ast_cli(fd, "No existence of '%s' context\n", argv[4]); break;
-
-                       case EEXIST:
-                               ast_cli(fd, "Extension %s@%s with priority %s already exists\n",
-                                       exten, argv[4], prior); break;
-
-                       default:
-                               ast_cli(fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n",
-                                       exten, prior, app, app_data, argv[4]); break;
+               case ENOMEM:
+                       ast_cli(a->fd, "Out of free memory\n");
+                       break;
+
+               case EBUSY:
+                       ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
+                       break;
+
+               case ENOENT:
+                       ast_cli(a->fd, "No existence of '%s' context\n", a->argv[5]);
+                       break;
+
+               case EEXIST:
+                       ast_cli(a->fd, "Extension %s@%s with priority %s already exists\n",
+                               exten, a->argv[5], prior);
+                       break;
+
+               default:
+                       ast_cli(a->fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n",
+                                       exten, prior, app, app_data, a->argv[5]);
+                       break;
                }
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
-       if (argc == 6) 
-               ast_cli(fd, "Extension %s@%s (%s) replace by '%s,%s,%s,%s'\n",
-                       exten, argv[4], prior, exten, prior, app, app_data);
+       if (a->argc == 7)
+               ast_cli(a->fd, "Extension %s@%s (%s) replace by '%s,%s,%s,%s'\n",
+                       exten, a->argv[5], prior, exten, prior, app, app_data);
        else
-               ast_cli(fd, "Extension '%s,%s,%s,%s' added into '%s' context\n",
-                       exten, prior, app, app_data, argv[4]);
+               ast_cli(a->fd, "Extension '%s,%s,%s,%s' added into '%s' context\n",
+                       exten, prior, app, app_data, a->argv[5]);
 
-       return RESULT_SUCCESS;
+       return CLI_SUCCESS;
 }
 
-/*! add extension 6123,1,Dial,IAX/212.71.138.13/6123 into local */
-static char *complete_context_add_extension(char *line, char *word,
-       int pos, int state)
+/*! dialplan add extension 6123,1,Dial,IAX/212.71.138.13/6123 into local */
+static char *complete_dialplan_add_extension(struct ast_cli_args *a)
 {
        int which = 0;
 
-       /* complete 'into' word ... */
-       if (pos == 3) {
-               if (state == 0) return strdup("into");
-               return NULL;
-       }
-
-       /* complete context */
-       if (pos == 4) {
-               struct ast_context *c;
+       if (a->pos == 4) {              /* complete 'into' word ... */
+               return (a->n == 0) ? strdup("into") : NULL;
+       } else if (a->pos == 5) { /* complete context */
+               struct ast_context *c = NULL;
+               int len = strlen(a->word);
+               char *res = NULL;
 
                /* try to lock contexts list ... */
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_WARNING, "Failed to lock contexts list\n");
                        return NULL;
                }
 
                /* walk through all contexts */
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       /* matching context? */
-                       if (!strncmp(ast_get_context_name(c), word, strlen(word))) {
-                               if (++which > state) {
-                                       char *res = strdup(ast_get_context_name(c));
-                                       ast_unlock_contexts();
-                                       return res;
-                               }
-                       }
-                       c = ast_walk_contexts(c);
-               }
-
+               while ( !res && (c = ast_walk_contexts(c)) )
+                       if (partial_match(ast_get_context_name(c), a->word, len) && ++which > a->n)
+                               res = strdup(ast_get_context_name(c));
                ast_unlock_contexts();
-               return NULL;
+               return res;
+       } else if (a->pos == 6) {
+               return a->n == 0 ? strdup("replace") : NULL;
        }
-
-       if (pos == 5) return state == 0 ? strdup("replace") : NULL;
-
        return NULL;
 }
 
 /*!
  * IGNOREPAT CLI stuff
  */
-static int handle_context_add_ignorepat(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_add_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 5) return RESULT_SHOWUSAGE;
-       if (strcmp(argv[3], "into")) return RESULT_SHOWUSAGE;
-
-       if (ast_context_add_ignorepat(argv[4], argv[2], registrar)) {
-               switch (errno) {
-                       case ENOMEM:
-                               ast_cli(fd, "Out of free memory\n"); break;
-
-                       case ENOENT:
-                               ast_cli(fd, "There is no existence of '%s' context\n", argv[4]);
-                               break;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan add ignorepat";
+               e->usage =
+                       "Usage: dialplan add ignorepat <pattern> into <context>\n"
+                       "       This command adds a new ignore pattern into context <context>\n"
+                       "\n"
+                       "Example: dialplan add ignorepat _3XX into local\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_add_ignorepat(a);
+       }
 
-                       case EEXIST:
-                               ast_cli(fd, "Ignore pattern '%s' already included in '%s' context\n",
-                                       argv[2], argv[4]);
-                               break;
+       if (a->argc != 6)
+               return CLI_SHOWUSAGE;
 
-                       case EBUSY:
-                               ast_cli(fd, "Failed to lock context(s) list, please, try again later\n");
-                               break;
+       if (strcmp(a->argv[4], "into"))
+               return CLI_SHOWUSAGE;
 
-                       default:
-                               ast_cli(fd, "Failed to add ingore pattern '%s' into '%s' context\n",
-                                       argv[2], argv[4]);
-                               break;
+       if (ast_context_add_ignorepat(a->argv[5], a->argv[3], registrar)) {
+               switch (errno) {
+               case ENOMEM:
+                       ast_cli(a->fd, "Out of free memory\n");
+                       break;
+
+               case ENOENT:
+                       ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
+                       break;
+
+               case EEXIST:
+                       ast_cli(a->fd, "Ignore pattern '%s' already included in '%s' context\n",
+                               a->argv[3], a->argv[5]);
+                       break;
+
+               case EBUSY:
+                       ast_cli(a->fd, "Failed to lock context(s) list, please, try again later\n");
+                       break;
+
+               default:
+                       ast_cli(a->fd, "Failed to add ingore pattern '%s' into '%s' context\n",
+                               a->argv[3], a->argv[5]);
+                       break;
                }
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
-       ast_cli(fd, "Ignore pattern '%s' added into '%s' context\n",
-               argv[2], argv[4]);
-       return RESULT_SUCCESS;
+       ast_cli(a->fd, "Ignore pattern '%s' added into '%s' context\n",
+               a->argv[3], a->argv[5]);
+
+       return CLI_SUCCESS;
 }
 
-static char *complete_context_add_ignorepat(char *line, char *word,
-       int pos, int state)
+static char *complete_dialplan_add_ignorepat(struct ast_cli_args *a)
 {
-       if (pos == 3) return state == 0 ? strdup("into") : NULL;
-
-       if (pos == 4) {
+       if (a->pos == 4)
+               return a->n == 0 ? strdup("into") : NULL;
+       else if (a->pos == 5) {
                struct ast_context *c;
                int which = 0;
-               char *dupline, *duplinet, *ignorepat = NULL;
-
-               dupline = strdup(line);
-               duplinet = dupline;
-
-               if (duplinet) {
-                       strsep(&duplinet, " "); /* skip 'add' */
-                       strsep(&duplinet, " "); /* skip 'ignorepat' */
-                       ignorepat = strsep(&duplinet, " ");
+               char *dupline, *ignorepat = NULL;
+               const char *s;
+               char *ret = NULL;
+               int len = strlen(a->word);
+
+               /* XXX skip first three words 'dialplan' 'add' 'ignorepat' */
+               s = skip_words(a->line, 3);
+               if (s == NULL)
+                       return NULL;
+               dupline = strdup(s);
+               if (!dupline) {
+                       ast_log(LOG_ERROR, "Malloc failure\n");
+                       return NULL;
                }
+               ignorepat = strsep(&dupline, " ");
 
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_ERROR, "Failed to lock contexts list\n");
                        return NULL;
                }
 
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       if (!strncmp(ast_get_context_name(c), word, strlen(word))) {
-                               int serve_context = 1;
-                               if (ignorepat) {
-                                       if (!ast_lock_context(c)) {
-                                               struct ast_ignorepat *ip;
-                                               ip = ast_walk_context_ignorepats(c, NULL);
-                                               while (ip && serve_context) {
-                                                       if (!strcmp(ast_get_ignorepat_name(ip), ignorepat))
-                                                               serve_context = 0;
-                                                       ip = ast_walk_context_ignorepats(c, ip);
-                                               }
-                                               ast_unlock_context(c);
-                                       }
-                               }
-                               if (serve_context) {
-                                       if (++which > state) {
-                                               char *context = strdup(ast_get_context_name(c));
-                                               if (dupline) free(dupline);
-                                               ast_unlock_contexts();
-                                               return context;
-                                       }
-                               }
-                       }
-                       c = ast_walk_contexts(c);
+               for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
+                       int found = 0;
+
+                       if (!partial_match(ast_get_context_name(c), a->word, len))
+                               continue; /* not mine */
+                       if (ignorepat) /* there must be one, right ? */
+                               found = lookup_c_ip(c, ignorepat);
+                       if (!found && ++which > a->n)
+                               ret = strdup(ast_get_context_name(c));
                }
 
-               if (dupline) free(dupline);
+               free(ignorepat);
                ast_unlock_contexts();
-               return NULL;
+               return ret;
        }
 
        return NULL;
 }
 
-static int handle_context_remove_ignorepat(int fd, int argc, char *argv[])
+static char *handle_cli_dialplan_remove_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 5) return RESULT_SHOWUSAGE;
-       if (strcmp(argv[3], "from")) return RESULT_SHOWUSAGE;
-
-       if (ast_context_remove_ignorepat(argv[4], argv[2], registrar)) {
-               switch (errno) {
-                       case EBUSY:
-                               ast_cli(fd, "Failed to lock context(s) list, please try again later\n");
-                               break;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan remove ignorepat";
+               e->usage =
+                       "Usage: dialplan remove ignorepat <pattern> from <context>\n"
+                       "       This command removes an ignore pattern from context <context>\n"
+                       "\n"
+                       "Example: dialplan remove ignorepat _3XX from local\n";
+               return NULL;
+       case CLI_GENERATE:
+               return complete_dialplan_remove_ignorepat(a);
+       }
 
-                       case ENOENT:
-                               ast_cli(fd, "There is no existence of '%s' context\n", argv[4]);
-                               break;
+       if (a->argc != 6)
+               return CLI_SHOWUSAGE;
 
-                       case EINVAL:
-                               ast_cli(fd, "There is no existence of '%s' ignore pattern in '%s' context\n",
-                                       argv[2], argv[4]);
-                               break;
+       if (strcmp(a->argv[4], "from"))
+               return CLI_SHOWUSAGE;
 
-                       default:
-                               ast_cli(fd, "Failed to remove ignore pattern '%s' from '%s' context\n", argv[2], argv[4]);
-                               break;
+       if (ast_context_remove_ignorepat(a->argv[5], a->argv[3], registrar)) {
+               switch (errno) {
+               case EBUSY:
+                       ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
+                       break;
+
+               case ENOENT:
+                       ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
+                       break;
+
+               case EINVAL:
+                       ast_cli(a->fd, "There is no existence of '%s' ignore pattern in '%s' context\n",
+                                       a->argv[3], a->argv[5]);
+                       break;
+
+               default:
+                       ast_cli(a->fd, "Failed to remove ignore pattern '%s' from '%s' context\n",
+                                       a->argv[3], a->argv[5]);
+                       break;
                }
-               return RESULT_FAILURE;
+               return CLI_FAILURE;
        }
 
-       ast_cli(fd, "Ignore pattern '%s' removed from '%s' context\n",
-               argv[2], argv[4]);
-       return RESULT_SUCCESS;
+       ast_cli(a->fd, "Ignore pattern '%s' removed from '%s' context\n",
+               a->argv[3], a->argv[5]);
+       return CLI_SUCCESS;
 }
 
-static int pbx_load_module(void);
-
-static int handle_reload_extensions(int fd, int argc, char *argv[])
-{
-       if (argc!=2) return RESULT_SHOWUSAGE;
-       pbx_load_module();
-       return RESULT_SUCCESS;
-}
-
-static char *complete_context_remove_ignorepat(char *line, char *word,
-       int pos, int state)
+static char *complete_dialplan_remove_ignorepat(struct ast_cli_args *a)
 {
        struct ast_context *c;
        int which = 0;
+       char *ret = NULL;
 
-       if (pos == 2) {
-               if (ast_lock_contexts()) {
+       if (a->pos == 3) {
+               int len = strlen(a->word);
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_WARNING, "Failed to lock contexts list\n");
                        return NULL;
                }
 
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       if (!ast_lock_context(c)) {
-                               struct ast_ignorepat *ip;
+               for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
+                       struct ast_ignorepat *ip;
+
+                       if (ast_rdlock_context(c))      /* error, skip it */
+                               continue;
                        
-                               ip = ast_walk_context_ignorepats(c, NULL);
-                               while (ip) {
-                                       if (!strncmp(ast_get_ignorepat_name(ip), word, strlen(word))) {
-                                               if (which + 1 > state) {
-                                                       struct ast_context *cw;
-                                                       int already_served = 0;
-                                                       cw = ast_walk_contexts(NULL);
-                                                       while (cw && cw != c && !already_served) {
-                                                               if (!ast_lock_context(cw)) {
-                                                                       struct ast_ignorepat *ipw;
-                                                                       ipw = ast_walk_context_ignorepats(cw, NULL);
-                                                                       while (ipw) {
-                                                                               if (!strcmp(ast_get_ignorepat_name(ipw),
-                                                                                       ast_get_ignorepat_name(ip))) already_served = 1;
-                                                                               ipw = ast_walk_context_ignorepats(cw, ipw);
-                                                                       }
-                                                                       ast_unlock_context(cw);
-                                                               }
-                                                               cw = ast_walk_contexts(cw);
-                                                       }
-                                                       if (!already_served) {
-                                                               char *ret = strdup(ast_get_ignorepat_name(ip));
-                                                               ast_unlock_context(c);
-                                                               ast_unlock_contexts();
-                                                               return ret;
-                                                       }
-                                               } else
-                                                       which++;
+                       for (ip = NULL; !ret && (ip = ast_walk_context_ignorepats(c, ip));) {
+                               if (partial_match(ast_get_ignorepat_name(ip), a->word, len) && ++which > a->n) {
+                                       /* n-th match */
+                                       struct ast_context *cw = NULL;
+                                       int found = 0;
+                                       while ( (cw = ast_walk_contexts(cw)) && cw != c && !found) {
+                                               /* XXX do i stop on c, or skip it ? */
+                                               found = lookup_c_ip(cw, ast_get_ignorepat_name(ip));
                                        }
-                                       ip = ast_walk_context_ignorepats(c, ip);
+                                       if (!found)
+                                               ret = strdup(ast_get_ignorepat_name(ip));
                                }
-
-                               ast_unlock_context(c);
                        }
-                       c = ast_walk_contexts(c);
+                       ast_unlock_context(c);
                }
-
                ast_unlock_contexts();
-               return NULL;
-       }
-       if (pos == 3) return state == 0 ? strdup("from") : NULL;
-
-       if (pos == 4) {
+               return ret;
+       } else if (a->pos == 4) {
+                return a->n == 0 ? strdup("from") : NULL;
+       } else if (a->pos == 5) { /* XXX check this */
                char *dupline, *duplinet, *ignorepat;
+               int len = strlen(a->word);
 
-               dupline = strdup(line);
+               dupline = strdup(a->line);
                if (!dupline) {
                        ast_log(LOG_WARNING, "Out of free memory\n");
                        return NULL;
@@ -1506,326 +1250,524 @@ static char *complete_context_remove_ignorepat(char *line, char *word,
                        return NULL;
                }
 
-               if (ast_lock_contexts()) {
+               if (ast_rdlock_contexts()) {
                        ast_log(LOG_WARNING, "Failed to lock contexts list\n");
                        free(dupline);
                        return NULL;
                }
 
-               c = ast_walk_contexts(NULL);
-               while (c) {
-                       if (!ast_lock_context(c)) {
-                               struct ast_ignorepat *ip;
-                               ip = ast_walk_context_ignorepats(c, NULL);
-                               while (ip) {
-                                       if (!strcmp(ast_get_ignorepat_name(ip), ignorepat)) {
-                                               if (!strncmp(ast_get_context_name(c), word, strlen(word))) {
-                                                       if (++which > state) {
-                                                               char *ret = strdup(ast_get_context_name(c));
-                                                               free(dupline);
-                                                               ast_unlock_context(c);
-                                                               ast_unlock_contexts();
-                                                               return ret;
-                                                       }
-                                               }
-                                       }
-                                       ip = ast_walk_context_ignorepats(c, ip);
-                               }
-
-                               ast_unlock_context(c);
-                       }
-                       c = ast_walk_contexts(c);
+               for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
+                       if (ast_rdlock_context(c))      /* fail, skip it */
+                               continue;
+                       if (!partial_match(ast_get_context_name(c), a->word, len))
+                               continue;
+                       if (lookup_c_ip(c, ignorepat) && ++which > a->n)
+                               ret = strdup(ast_get_context_name(c));
+                       ast_unlock_context(c);
                }
-
-               free(dupline);
                ast_unlock_contexts();
+               free(dupline);
                return NULL;
        }
 
        return NULL;
 }
 
+static int pbx_load_module(void);
+
+static char *handle_cli_dialplan_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "dialplan reload";
+               e->usage =
+                       "Usage: dialplan reload\n"
+                       "       Reload extensions.conf without reloading any other\n"
+                       "       modules.  This command does not delete global variables\n"
+                       "       unless clearglobalvars is set to yes in extensions.conf\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (a->argc != 2)
+               return CLI_SHOWUSAGE;
+
+       if (clearglobalvars_config)
+               pbx_builtin_clear_globals();
+
+       pbx_load_module();
+       ast_cli(a->fd, "Dialplan reloaded.\n");
+       return CLI_SUCCESS;
+}
+
 /*!
  * CLI entries for commands provided by this module
  */
-static struct ast_cli_entry context_dont_include_cli =
-       { { "dont", "include", NULL }, handle_context_dont_include,
-               "Remove a specified include from context", context_dont_include_help,
-               complete_context_dont_include };
-
-static struct ast_cli_entry context_remove_extension_cli =
-       { { "remove", "extension", NULL }, handle_context_remove_extension,
-               "Remove a specified extension", context_remove_extension_help,
-               complete_context_remove_extension };
-
-static struct ast_cli_entry context_add_include_cli =
-       { { "include", "context", NULL }, handle_context_add_include,
-               "Include context in other context", context_add_include_help,
-               complete_context_add_include };
-
-static struct ast_cli_entry save_dialplan_cli =
-       { { "save", "dialplan", NULL }, handle_save_dialplan,
-               "Save dialplan", save_dialplan_help };
-
-static struct ast_cli_entry context_add_extension_cli =
-       { { "add", "extension", NULL }, handle_context_add_extension,
-               "Add new extension into context", context_add_extension_help,
-               complete_context_add_extension };
-
-static struct ast_cli_entry context_add_ignorepat_cli =
-       { { "add", "ignorepat", NULL }, handle_context_add_ignorepat,
-               "Add new ignore pattern", context_add_ignorepat_help,
-               complete_context_add_ignorepat };
-
-static struct ast_cli_entry context_remove_ignorepat_cli =
-       { { "remove", "ignorepat", NULL }, handle_context_remove_ignorepat,
-               "Remove ignore pattern from context", context_remove_ignorepat_help,
-               complete_context_remove_ignorepat };
-
-static struct ast_cli_entry reload_extensions_cli = 
-       { { "extensions", "reload", NULL}, handle_reload_extensions,
-               "Reload extensions and *only* extensions", reload_extensions_help };
+static struct ast_cli_entry cli_pbx_config[] = {
+       AST_CLI_DEFINE(handle_cli_dialplan_add_extension,    "Add new extension into context"),
+       AST_CLI_DEFINE(handle_cli_dialplan_remove_extension, "Remove a specified extension"),
+       AST_CLI_DEFINE(handle_cli_dialplan_add_ignorepat,    "Add new ignore pattern"),
+       AST_CLI_DEFINE(handle_cli_dialplan_remove_ignorepat, "Remove ignore pattern from context"),
+       AST_CLI_DEFINE(handle_cli_dialplan_add_include,      "Include context in other context"),
+       AST_CLI_DEFINE(handle_cli_dialplan_remove_include,   "Remove a specified include from context"),
+       AST_CLI_DEFINE(handle_cli_dialplan_reload,           "Reload extensions and *only* extensions")
+};
+
+static struct ast_cli_entry cli_dialplan_save =
+       AST_CLI_DEFINE(handle_cli_dialplan_save, "Save dialplan");
 
 /*!
  * Standard module functions ...
  */
-int unload_module(void)
+static int unload_module(void)
 {
-       ast_cli_unregister(&context_add_extension_cli);
        if (static_config && !write_protect_config)
-               ast_cli_unregister(&save_dialplan_cli);
-       ast_cli_unregister(&context_add_include_cli);
-       ast_cli_unregister(&context_dont_include_cli);
-       ast_cli_unregister(&context_remove_extension_cli);
-       ast_cli_unregister(&context_remove_ignorepat_cli);
-       ast_cli_unregister(&context_add_ignorepat_cli);
-       ast_cli_unregister(&reload_extensions_cli);
+               ast_cli_unregister(&cli_dialplan_save);
+       if (overrideswitch_config) {
+               ast_free(overrideswitch_config);
+       }
+       ast_cli_unregister_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
        ast_context_destroy(NULL, registrar);
        return 0;
 }
 
-static int pbx_load_module(void)
+/*!\note Protect against misparsing based upon commas in the middle of fields
+ * like character classes.  We've taken steps to permit pretty much every other
+ * printable character in a character class, so properly handling a comma at
+ * this level is a natural extension.  This is almost like the standard
+ * application parser in app.c, except that it handles square brackets. */
+static char *pbx_strsep(char **destructible, const char *delim)
+{
+       int square = 0;
+       char *res = *destructible;
+       for (; destructible && *destructible && **destructible; (*destructible)++) {
+               if (**destructible == '[' && !strchr(delim, '[')) {
+                       square++;
+               } else if (**destructible == ']' && !strchr(delim, ']')) {
+                       if (square) {
+                               square--;
+                       }
+               } else if (**destructible == '\\' && !strchr(delim, '\\')) {
+                       (*destructible)++;
+               } else if (strchr(delim, **destructible) && !square) {
+                       **destructible = '\0';
+                       (*destructible)++;
+                       break;
+               }
+       }
+       if (destructible && *destructible && **destructible == '\0') {
+               *destructible = NULL;
+       }
+       return res;
+}
+
+static int pbx_load_config(const char *config_file)
 {
        struct ast_config *cfg;
-       struct ast_variable *v;
-       char *cxt, *ext, *pri, *appl, *data, *tc, *cidmatch;
-       struct ast_context *con;
        char *end;
        char *label;
+#ifdef LOW_MEMORY
        char realvalue[256];
+#else
+       char realvalue[8192];
+#endif
        int lastpri = -2;
+       struct ast_context *con;
+       struct ast_variable *v;
+       const char *cxt;
+       const char *aft;
+       const char *newpm, *ovsw;
+       struct ast_flags config_flags = { 0 };
+       char lastextension[256];
+       cfg = ast_config_load(config_file, config_flags);
+       if (!cfg || cfg == CONFIG_STATUS_FILEINVALID)
+               return 0;
 
-       cfg = ast_config_load(config);
-       if (cfg) {
-               /* Use existing config to populate the PBX table */
-               static_config = ast_true(ast_variable_retrieve(cfg, "general",
-                                                              "static"));
-               write_protect_config = ast_true(ast_variable_retrieve(cfg, "general",
-                                                                     "writeprotect"));
-               autofallthrough_config = ast_true(ast_variable_retrieve(cfg, "general",
-                                                                       "autofallthrough"));
-               clearglobalvars_config = ast_true(ast_variable_retrieve(cfg, "general", 
-                                                                       "clearglobalvars"));
-               option_priority_jumping = !ast_false(ast_variable_retrieve(cfg, "general",
-                                                                          "priorityjumping"));
-
-               v = ast_variable_browse(cfg, "globals");
-               while(v) {
-                       memset(realvalue, 0, sizeof(realvalue));
-                       pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
-                       pbx_builtin_setvar_helper(NULL, v->name, realvalue);
-                       v = v->next;
+       /* Use existing config to populate the PBX table */
+       static_config = ast_true(ast_variable_retrieve(cfg, "general", "static"));
+       write_protect_config = ast_true(ast_variable_retrieve(cfg, "general", "writeprotect"));
+       if ((aft = ast_variable_retrieve(cfg, "general", "autofallthrough")))
+               autofallthrough_config = ast_true(aft);
+       if ((newpm = ast_variable_retrieve(cfg, "general", "extenpatternmatchnew")))
+               extenpatternmatchnew_config = ast_true(newpm);
+       clearglobalvars_config = ast_true(ast_variable_retrieve(cfg, "general", "clearglobalvars"));
+       if ((ovsw = ast_variable_retrieve(cfg, "general", "overrideswitch"))) {
+               if (overrideswitch_config) {
+                       ast_free(overrideswitch_config);
                }
-               cxt = ast_category_browse(cfg, NULL);
-               while(cxt) {
-                       /* All categories but "general" or "globals" are considered contexts */
-                       if (!strcasecmp(cxt, "general") || !strcasecmp(cxt, "globals")) {
-                               cxt = ast_category_browse(cfg, cxt);
-                               continue;
-                       }
-                       if ((con=ast_context_create(&local_contexts,cxt, registrar))) {
-                               v = ast_variable_browse(cfg, cxt);
-                               while(v) {
-                                       if (!strcasecmp(v->name, "exten")) {
-                                               char *stringp=NULL;
-                                               int ipri = -2;
-                                               char realext[256]="";
-                                               char *plus, *firstp, *firstc;
-                                               tc = strdup(v->value);
-                                               if(tc!=NULL){
-                                                       stringp=tc;
-                                                       ext = strsep(&stringp, ",");
-                                                       if (!ext)
-                                                               ext="";
-                                                       pbx_substitute_variables_helper(NULL, ext, realext, sizeof(realext) - 1);
-                                                       cidmatch = strchr(realext, '/');
-                                                       if (cidmatch) {
-                                                               *cidmatch = '\0';
-                                                               cidmatch++;
-                                                               ast_shrink_phone_number(cidmatch);
-                                                       }
-                                                       pri = strsep(&stringp, ",");
-                                                       if (!pri)
-                                                               pri="";
-                                                       label = strchr(pri, '(');
-                                                       if (label) {
-                                                               *label = '\0';
-                                                               label++;
-                                                               end = strchr(label, ')');
-                                                               if (end)
-                                                                       *end = '\0';
-                                                               else
-                                                                       ast_log(LOG_WARNING, "Label missing trailing ')' at line %d\n", v->lineno);
-                                                       }
-                                                       plus = strchr(pri, '+');
-                                                       if (plus) {
-                                                               *plus = '\0';
-                                                               plus++;
-                                                       }
-                                                       if (!strcmp(pri,"hint"))
-                                                               ipri=PRIORITY_HINT;
-                                                       else if (!strcmp(pri, "next") || !strcmp(pri, "n")) {
-                                                               if (lastpri > -2)
-                                                                       ipri = lastpri + 1;
-                                                               else
-                                                                       ast_log(LOG_WARNING, "Can't use 'next' priority on the first entry!\n");
-                                                       } else if (!strcmp(pri, "same") || !strcmp(pri, "s")) {
-                                                               if (lastpri > -2)
-                                                                       ipri = lastpri;
-                                                               else
-                                                                       ast_log(LOG_WARNING, "Can't use 'same' priority on the first entry!\n");
-                                                       } else  {
-                                                               if (sscanf(pri, "%d", &ipri) != 1) {
-                                                                       if ((ipri = ast_findlabel_extension2(NULL, con, realext, pri, cidmatch)) < 1) {
-                                                                               ast_log(LOG_WARNING, "Invalid priority/label '%s' at line %d\n", pri, v->lineno);
-                                                                               ipri = 0;
-                                                                       }
-                                                               }
-                                                       }
-                                                       appl = stringp;
-                                                       if (!appl)
-                                                               appl="";
-                                                       /* Find the first occurrence of either '(' or ',' */
-                                                       firstc = strchr(appl, ',');
-                                                       firstp = strchr(appl, '(');
-                                                       if (firstc && ((!firstp) || (firstc < firstp))) {
-                                                               /* comma found, no parenthesis */
-                                                               /* or both found, but comma found first */
-                                                               appl = strsep(&stringp, ",");
-                                                               data = stringp;
-                                                       } else if ((!firstc) && (!firstp)) {
-                                                               /* Neither found */
-                                                               data = "";
-                                                       } else {
-                                                               /* Final remaining case is parenthesis found first */
-                                                               appl = strsep(&stringp, "(");
-                                                               data = stringp;
-                                                               end = strrchr(data, ')');
-                                                               if ((end = strrchr(data, ')'))) {
-                                                                       *end = '\0';
-                                                               } else {
-                                                                       ast_log(LOG_WARNING, "No closing parenthesis found? '%s(%s'\n", appl, data);
-                                                               }
-                                                               ast_process_quotes_and_slashes(data, ',', '|');
-                                                       }
+               if (!ast_strlen_zero(ovsw)) {
+                       overrideswitch_config = ast_strdup(ovsw);
+               } else {
+                       overrideswitch_config = NULL;
+               }
+       }
 
-                                                       if (!data)
-                                                               data="";
-                                                       while(*appl && (*appl < 33)) appl++;
-                                                       if (ipri) {
-                                                               if (plus)
-                                                                       ipri += atoi(plus);
-                                                               lastpri = ipri;
-                                                               if(!option_dontwarn) {
-                                                                       if (!strcmp(realext, "_."))
-                                                                               ast_log(LOG_WARNING, "The use of '_.' for an extension is strongly discouraged and can have unexpected behavior.  Please use '_X.' instead at line %d\n", v->lineno);
-                                                               }
-                                                               if (ast_add_extension2(con, 0, realext, ipri, label, cidmatch, appl, strdup(data), FREE, registrar)) {
-                                                                       ast_log(LOG_WARNING, "Unable to register extension at line %d\n", v->lineno);
-                                                               }
-                                                       }
-                                                       free(tc);
-                                               } else fprintf(stderr,"Error strdup returned NULL in %s\n",__PRETTY_FUNCTION__);
-                                       } else if(!strcasecmp(v->name, "include")) {
-                                               memset(realvalue, 0, sizeof(realvalue));
-                                               pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
-                                               if (ast_context_add_include2(con, realvalue, registrar))
-                                                       ast_log(LOG_WARNING, "Unable to include context '%s' in context '%s'\n", v->value, cxt);
-                                       } else if(!strcasecmp(v->name, "ignorepat")) {
-                                               memset(realvalue, 0, sizeof(realvalue));
-                                               pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
-                                               if (ast_context_add_ignorepat2(con, realvalue, registrar))
-                                                       ast_log(LOG_WARNING, "Unable to include ignorepat '%s' in context '%s'\n", v->value, cxt);
-                                       } else if (!strcasecmp(v->name, "switch") || !strcasecmp(v->name, "lswitch") || !strcasecmp(v->name, "eswitch")) {
-                                               char *stringp=NULL;
-                                               memset(realvalue, 0, sizeof(realvalue));
-                                               if (!strcasecmp(v->name, "switch"))
-                                                       pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
-                                               else
-                                                       strncpy(realvalue, v->value, sizeof(realvalue) - 1);
-                                               tc = realvalue;
-                                               stringp=tc;
-                                               appl = strsep(&stringp, "/");
-                                               data = strsep(&stringp, "");
-                                               if (!data)
-                                                       data = "";
-                                               if (ast_context_add_switch2(con, appl, data, !strcasecmp(v->name, "eswitch"), registrar))
-                                                       ast_log(LOG_WARNING, "Unable to include switch '%s' in context '%s'\n", v->value, cxt);
+       ast_copy_string(userscontext, ast_variable_retrieve(cfg, "general", "userscontext") ?: "default", sizeof(userscontext));
+                                                                   
+       for (v = ast_variable_browse(cfg, "globals"); v; v = v->next) {
+               pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
+               pbx_builtin_setvar_helper(NULL, v->name, realvalue);
+       }
+       for (cxt = ast_category_browse(cfg, NULL);
+            cxt;
+            cxt = ast_category_browse(cfg, cxt)) {
+               /* All categories but "general" or "globals" are considered contexts */
+               if (!strcasecmp(cxt, "general") || !strcasecmp(cxt, "globals")) {
+                       continue;
+               }
+               if (!(con = ast_context_find_or_create(&local_contexts, local_table, cxt, registrar))) {
+                       continue;
+               }
+
+               /* Reset continuation items at the beginning of each context */
+               lastextension[0] = '\0';
+               lastpri = -2;
+
+               for (v = ast_variable_browse(cfg, cxt); v; v = v->next) {
+                       char *tc = NULL;
+                       char realext[256] = "";
+                       char *stringp, *ext;
+
+                       if (!strncasecmp(v->name, "same", 4)) {
+                               if (ast_strlen_zero(lastextension)) {
+                                       ast_log(LOG_ERROR, "No previous pattern in the first entry of context '%s' to match '%s' at line %d!\n", cxt, v->name, v->lineno);
+                                       continue;
+                               }
+                               if ((stringp = tc = ast_strdup(v->value))) {
+                                       ast_copy_string(realext, lastextension, sizeof(realext));
+                                       goto process_extension;
+                               }
+                       } else if (!strcasecmp(v->name, "exten")) {
+                               int ipri;
+                               char *plus, *firstp;
+                               char *pri, *appl, *data, *cidmatch;
+
+                               if (!(stringp = tc = ast_strdup(v->value))) {
+                                       continue;
+                               }
+
+                               ext = S_OR(pbx_strsep(&stringp, ","), "");
+                               pbx_substitute_variables_helper(NULL, ext, realext, sizeof(realext) - 1);
+                               ast_copy_string(lastextension, realext, sizeof(lastextension));
+process_extension:
+                               ipri = -2;
+                               if ((cidmatch = strchr(realext, '/'))) {
+                                       *cidmatch++ = '\0';
+                                       ast_shrink_phone_number(cidmatch);
+                               }
+                               pri = ast_strip(S_OR(strsep(&stringp, ","), ""));
+                               if ((label = strchr(pri, '('))) {
+                                       *label++ = '\0';
+                                       if ((end = strchr(label, ')'))) {
+                                               *end = '\0';
+                                       } else {
+                                               ast_log(LOG_WARNING, "Label missing trailing ')' at line %d\n", v->lineno);
+                                               ast_free(tc);
+                                               continue;
+                                       }
+                               }
+                               if ((plus = strchr(pri, '+'))) {
+                                       *plus++ = '\0';
+                               }
+                               if (!strcmp(pri,"hint")) {
+                                       ipri = PRIORITY_HINT;
+                               } else if (!strcmp(pri, "next") || !strcmp(pri, "n")) {
+                                       if (lastpri > -2) {
+                                               ipri = lastpri + 1;
+                                       } else {
+                                               ast_log(LOG_WARNING, "Can't use 'next' priority on the first entry at line %d!\n", v->lineno);
+                                               ast_free(tc);
+                                               continue;
+                                       }
+                               } else if (!strcmp(pri, "same") || !strcmp(pri, "s")) {
+                                       if (lastpri > -2) {
+                                               ipri = lastpri;
+                                       } else {
+                                               ast_log(LOG_WARNING, "Can't use 'same' priority on the first entry at line %d!\n", v->lineno);
+                                               ast_free(tc);
+                                               continue;
+                                       }
+                               } else if (sscanf(pri, "%30d", &ipri) != 1 &&
+                                          (ipri = ast_findlabel_extension2(NULL, con, realext, pri, cidmatch)) < 1) {
+                                       ast_log(LOG_WARNING, "Invalid priority/label '%s' at line %d\n", pri, v->lineno);
+                                       ipri = 0;
+                                       ast_free(tc);
+                                       continue;
+                               } else if (ipri < 1) {
+                                       ast_log(LOG_WARNING, "Invalid priority '%s' at line %d\n", pri, v->lineno);
+                                       ast_free(tc);
+                                       continue;
+                               }
+                               appl = S_OR(stringp, "");
+                               /* Find the first occurrence of '(' */
+                               if (!(firstp = strchr(appl, '('))) {
+                                       /* No arguments */
+                                       data = "";
+                               } else {
+                                       char *orig_appl = ast_strdup(appl);
+
+                                       if (!orig_appl) {
+                                               ast_free(tc);
+                                               continue;
+                                       }
+
+                                       appl = strsep(&stringp, "(");
+
+                                       /* check if there are variables or expressions without an application, like: exten => 100,hint,DAHDI/g0/${GLOBAL(var)}  */
+                                       if (strstr(appl, "${") || strstr(appl, "$[")){
+                                               /* set appl to original one */
+                                               strcpy(appl, orig_appl);
+                                               /* set no data */
+                                               data = "";
+                                       /* no variable before application found -> go ahead */
+                                       } else {
+                                               data = S_OR(stringp, "");
+                                               if ((end = strrchr(data, ')'))) {
+                                                       *end = '\0';
+                                               } else {
+                                                       ast_log(LOG_WARNING, "No closing parenthesis found? '%s(%s' at line %d\n", appl, data, v->lineno);
+                                               }
                                        }
-                                       v = v->next;
+                                       ast_free(orig_appl);
+                               }
+
+                               appl = ast_skip_blanks(appl);
+                               if (ipri) {
+                                       if (plus) {
+                                               ipri += atoi(plus);
+                                       }
+                                       lastpri = ipri;
+                                       if (!ast_opt_dont_warn && (!strcmp(realext, "_.") || !strcmp(realext, "_!"))) {
+                                               ast_log(LOG_WARNING, "The use of '%s' for an extension is strongly discouraged and can have unexpected behavior.  Please use '_X%c' instead at line %d\n", realext, realext[1], v->lineno);
+                                       }
+                                       if (ast_add_extension2(con, 0, realext, ipri, label, cidmatch, appl, strdup(data), ast_free_ptr, registrar)) {
+                                               ast_log(LOG_WARNING, "Unable to register extension at line %d\n", v->lineno);
+                                       }
+                               }
+                               free(tc);
+                       } else if (!strcasecmp(v->name, "include")) {
+                               pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
+                               if (ast_context_add_include2(con, realvalue, registrar)) {
+                                       switch (errno) {
+                                               case ENOMEM:
+                                                       ast_log(LOG_WARNING, "Out of memory for context addition\n");
+                                                       break;
+
+                                               case EBUSY:
+                                                       ast_log(LOG_WARNING, "Failed to lock context(s) list, please try again later\n");
+                                                       break;
+
+                                               case EEXIST:
+                                                       ast_log(LOG_WARNING, "Context '%s' already included in '%s' context on include at line %d\n",
+                                                                       v->value, cxt, v->lineno);
+                                                       break;
+
+                                               case ENOENT:
+                                               case EINVAL:
+                                                       ast_log(LOG_WARNING, "There is no existence of context '%s' included at line %d\n",
+                                                                       errno == ENOENT ? v->value : cxt, v->lineno);
+                                                       break;
+
+                                               default:
+                                                       ast_log(LOG_WARNING, "Failed to include '%s' in '%s' context at line %d\n",
+                                                                       v->value, cxt, v->lineno);
+                                                       break;
+                                       }
+                               }
+                       } else if (!strcasecmp(v->name, "ignorepat")) {
+                               pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
+                               if (ast_context_add_ignorepat2(con, realvalue, registrar)) {
+                                       ast_log(LOG_WARNING, "Unable to include ignorepat '%s' in context '%s' at line %d\n", v->value, cxt, v->lineno);
+                               }
+                       } else if (!strcasecmp(v->name, "switch") || !strcasecmp(v->name, "lswitch") || !strcasecmp(v->name, "eswitch")) {
+                               char *stringp = realvalue;
+                               char *appl, *data;
+                               
+                               if (!strcasecmp(v->name, "switch")) {
+                                       pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
+                               } else {
+                                       ast_copy_string(realvalue, v->value, sizeof(realvalue));
+                               }
+                               appl = strsep(&stringp, "/");
+                               data = S_OR(stringp, "");
+                               if (ast_context_add_switch2(con, appl, data, !strcasecmp(v->name, "eswitch"), registrar)) {
+                                       ast_log(LOG_WARNING, "Unable to include switch '%s' in context '%s' at line %d\n", v->value, cxt, v->lineno);
+                               }
+                       } else {
+                               ast_log(LOG_WARNING, "==!!== Unknown directive: %s at line %d -- IGNORING!!!\n", v->name, v->lineno);
+                       }
+               }
+       }
+       ast_config_destroy(cfg);
+       return 1;
+}
+
+static void append_interface(char *iface, int maxlen, char *add)
+{
+       int len = strlen(iface);
+       if (strlen(add) + len < maxlen - 2) {
+               if (strlen(iface)) {
+                       iface[len] = '&';
+                       strcpy(iface + len + 1, add);
+               } else
+                       strcpy(iface, add);
+       }
+}
+
+static void pbx_load_users(void)
+{
+       struct ast_config *cfg;
+       char *cat, *chan;
+       const char *dahdichan;
+       const char *hasexten, *altexts;
+       char tmp[256];
+       char iface[256];
+       char dahdicopy[256];
+       char *ext, altcopy[256];
+       char *c;
+       int len;
+       int hasvoicemail;
+       int start, finish, x;
+       struct ast_context *con = NULL;
+       struct ast_flags config_flags = { 0 };
+       
+       cfg = ast_config_load("users.conf", config_flags);
+       if (!cfg)
+               return;
+
+       for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
+               if (!strcasecmp(cat, "general"))
+                       continue;
+               iface[0] = '\0';
+               len = sizeof(iface);
+               if (ast_true(ast_config_option(cfg, cat, "hassip"))) {
+                       snprintf(tmp, sizeof(tmp), "SIP/%s", cat);
+                       append_interface(iface, sizeof(iface), tmp);
+               }
+               if (ast_true(ast_config_option(cfg, cat, "hasiax"))) {
+                       snprintf(tmp, sizeof(tmp), "IAX2/%s", cat);
+                       append_interface(iface, sizeof(iface), tmp);
+               }
+               if (ast_true(ast_config_option(cfg, cat, "hash323"))) {
+                       snprintf(tmp, sizeof(tmp), "H323/%s", cat);
+                       append_interface(iface, sizeof(iface), tmp);
+               }
+               hasexten = ast_config_option(cfg, cat, "hasexten");
+               if (hasexten && !ast_true(hasexten))
+                       continue;
+               hasvoicemail = ast_true(ast_config_option(cfg, cat, "hasvoicemail"));
+               dahdichan = ast_variable_retrieve(cfg, cat, "dahdichan");
+               if (!dahdichan)
+                       dahdichan = ast_variable_retrieve(cfg, "general", "dahdichan");
+               if (!ast_strlen_zero(dahdichan)) {
+                       ast_copy_string(dahdicopy, dahdichan, sizeof(dahdicopy));
+                       c = dahdicopy;
+                       chan = strsep(&c, ",");
+                       while (chan) {
+                               if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
+                                       /* Range */
+                               } else if (sscanf(chan, "%30d", &start)) {
+                                       /* Just one */
+                                       finish = start;
+                               } else {
+                                       start = 0; finish = 0;
+                               }
+                               if (finish < start) {
+                                       x = finish;
+                                       finish = start;
+                                       start = x;
+                               }
+                               for (x = start; x <= finish; x++) {
+                                       snprintf(tmp, sizeof(tmp), "DAHDI/%d", x);
+                                       append_interface(iface, sizeof(iface), tmp);
+                               }
+                               chan = strsep(&c, ",");
+                       }
+               }
+               if (!ast_strlen_zero(iface)) {
+                       /* Only create a context here when it is really needed. Otherwise default empty context
+                       created by pbx_config may conflict with the one explicitly created by pbx_ael */
+                       if (!con)
+                               con = ast_context_find_or_create(&local_contexts, local_table, userscontext, registrar);
+
+                       if (!con) {
+                               ast_log(LOG_ERROR, "Can't find/create user context '%s'\n", userscontext);
+                               return;
+                       }
+
+                       /* Add hint */
+                       ast_add_extension2(con, 0, cat, -1, NULL, NULL, iface, NULL, NULL, registrar);
+                       /* If voicemail, use "stdexten" else use plain old dial */
+                       if (hasvoicemail) {
+                               snprintf(tmp, sizeof(tmp), "stdexten,%s,${HINT}", cat);
+                               ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Macro", strdup(tmp), ast_free_ptr, registrar);
+                       } else {
+                               ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Dial", strdup("${HINT}"), ast_free_ptr, registrar);
+                       }
+                       altexts = ast_variable_retrieve(cfg, cat, "alternateexts");
+                       if (!ast_strlen_zero(altexts)) {
+                               snprintf(tmp, sizeof(tmp), "%s,1", cat);
+                               ast_copy_string(altcopy, altexts, sizeof(altcopy));
+                               c = altcopy;
+                               ext = strsep(&c, ",");
+                               while (ext) {
+                                       ast_add_extension2(con, 0, ext, 1, NULL, NULL, "Goto", strdup(tmp), ast_free_ptr, registrar);
+                                       ext = strsep(&c, ",");
                                }
                        }
-                       cxt = ast_category_browse(cfg, cxt);
                }
-               ast_config_destroy(cfg);
        }
-       ast_merge_contexts_and_delete(&local_contexts,registrar);
+       ast_config_destroy(cfg);
+}
+
+static int pbx_load_module(void)
+{
+       struct ast_context *con;
+
+       if (!local_table)
+               local_table = ast_hashtab_create(17, ast_hashtab_compare_contexts, ast_hashtab_resize_java, ast_hashtab_newsize_java, ast_hashtab_hash_contexts, 0);
+
+       if (!pbx_load_config(config))
+               return AST_MODULE_LOAD_DECLINE;
+       
+       pbx_load_users();
+
+       ast_merge_contexts_and_delete(&local_contexts, local_table, registrar);
+       local_table = NULL; /* the local table has been moved into the global one. */
+       local_contexts = NULL;
 
-       for (con = ast_walk_contexts(NULL); con; con = ast_walk_contexts(con))
+       for (con = NULL; (con = ast_walk_contexts(con));)
                ast_context_verify_includes(con);
 
+       pbx_set_overrideswitch(overrideswitch_config);
        pbx_set_autofallthrough(autofallthrough_config);
+       pbx_set_extenpatternmatchnew(extenpatternmatchnew_config);
 
-       return 0;
+       return AST_MODULE_LOAD_SUCCESS;
 }
 
-int load_module(void)
+static int load_module(void)
 {
-       if (pbx_load_module()) return -1;
-       ast_cli_register(&context_remove_extension_cli);
-       ast_cli_register(&context_dont_include_cli);
-       ast_cli_register(&context_add_include_cli);
        if (static_config && !write_protect_config)
-               ast_cli_register(&save_dialplan_cli);
-       ast_cli_register(&context_add_extension_cli);
-       ast_cli_register(&context_add_ignorepat_cli);
-       ast_cli_register(&context_remove_ignorepat_cli);
-       ast_cli_register(&reload_extensions_cli);
+               ast_cli_register(&cli_dialplan_save);
+       ast_cli_register_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
 
-       return 0;
+       if (pbx_load_module())
+               return AST_MODULE_LOAD_DECLINE;
+
+       return AST_MODULE_LOAD_SUCCESS;
 }
 
-int reload(void)
+static int reload(void)
 {
-       ast_context_destroy(NULL, registrar);
        if (clearglobalvars_config)
                pbx_builtin_clear_globals();
-       pbx_load_module();
-       return 0;
-}
-
-int usecount(void)
-{
-       return 0;
-}
-
-char *description(void)
-{
-       return dtext;
+       return pbx_load_module();
 }
 
-char *key(void)
-{
-       return ASTERISK_GPL_KEY;
-}
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Text Extension Configuration",
+               .load = load_module,
+               .unload = unload_module,
+               .reload = reload,
+              );