]> granicus.if.org Git - esp-idf/commitdiff
add console component and example
authorIvan Grokhotkov <ivan@espressif.com>
Tue, 15 Aug 2017 08:11:19 +0000 (16:11 +0800)
committerIvan Grokhotkov <ivan@espressif.com>
Mon, 21 Aug 2017 07:58:27 +0000 (15:58 +0800)
23 files changed:
components/console/argtable3/LICENSE [new file with mode: 0644]
components/console/argtable3/argtable3.c [new file with mode: 0644]
components/console/argtable3/argtable3.h [new file with mode: 0644]
components/console/commands.c [new file with mode: 0644]
components/console/component.mk [new file with mode: 0644]
components/console/esp_console.h [new file with mode: 0644]
components/console/linenoise/LICENSE [new file with mode: 0644]
components/console/linenoise/linenoise.c [new file with mode: 0644]
components/console/linenoise/linenoise.h [new file with mode: 0644]
components/console/split_argv.c [new file with mode: 0644]
docs/COPYRIGHT.rst
docs/api-guides/console.rst [new file with mode: 0644]
docs/api-guides/index.rst
examples/system/console/Makefile [new file with mode: 0644]
examples/system/console/README.md [new file with mode: 0644]
examples/system/console/main/Kconfig.projbuild [new file with mode: 0644]
examples/system/console/main/cmd_decl.h [new file with mode: 0644]
examples/system/console/main/cmd_system.c [new file with mode: 0644]
examples/system/console/main/cmd_wifi.c [new file with mode: 0644]
examples/system/console/main/component.mk [new file with mode: 0644]
examples/system/console/main/console_example_main.c [new file with mode: 0644]
examples/system/console/partitions_example.csv [new file with mode: 0644]
examples/system/console/sdkconfig.defaults [new file with mode: 0644]

diff --git a/components/console/argtable3/LICENSE b/components/console/argtable3/LICENSE
new file mode 100644 (file)
index 0000000..1a28ef9
--- /dev/null
@@ -0,0 +1,26 @@
+Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+<sheitmann@users.sourceforge.net>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of STEWART HEITMANN nor the  names of its contributors
+      may be used to endorse or promote products derived from this software
+      without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
diff --git a/components/console/argtable3/argtable3.c b/components/console/argtable3/argtable3.c
new file mode 100644 (file)
index 0000000..a5eed4d
--- /dev/null
@@ -0,0 +1,4953 @@
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include "argtable3.h"
+
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 2013 Tom G. Huang
+ * <tomghuang@gmail.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#ifndef ARG_UTILS_H
+#define ARG_UTILS_H
+
+#define ARG_ENABLE_TRACE 0
+#define ARG_ENABLE_LOG 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum
+{
+    EMINCOUNT = 1,
+    EMAXCOUNT,
+    EBADINT,
+    EOVERFLOW,
+    EBADDOUBLE,
+    EBADDATE,
+    EREGNOMATCH
+};
+
+
+#if defined(_MSC_VER)
+#define ARG_TRACE(x) \
+    __pragma(warning(push)) \
+    __pragma(warning(disable:4127)) \
+    do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0) \
+    __pragma(warning(pop))
+
+#define ARG_LOG(x) \
+    __pragma(warning(push)) \
+    __pragma(warning(disable:4127)) \
+    do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0) \
+    __pragma(warning(pop))
+#else
+#define ARG_TRACE(x) \
+    do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0)
+
+#define ARG_LOG(x) \
+    do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0)
+#endif 
+
+extern void dbg_printf(const char *fmt, ...);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdarg.h>
+#include <stdio.h>
+
+
+void dbg_printf(const char *fmt, ...)
+{
+    va_list args;
+    va_start(args, fmt);
+    vfprintf(stderr, fmt, args);
+    va_end(args);
+}
+
+/*     $Id: getopt.h,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
+/*     $OpenBSD: getopt.h,v 1.1 2002/12/03 20:24:29 millert Exp $      */
+/*     $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $    */
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *        This product includes software developed by the NetBSD
+ *        Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _GETOPT_H_
+#define _GETOPT_H_
+
+#if 0
+#include <sys/cdefs.h>
+#endif
+
+/*
+ * GNU-like getopt_long() and 4.4BSD getsubopt()/optreset extensions
+ */
+#define no_argument        0
+#define required_argument  1
+#define optional_argument  2
+
+struct option {
+       /* name of long option */
+       const char *name;
+       /*
+        * one of no_argument, required_argument, and optional_argument:
+        * whether option takes an argument
+        */
+       int has_arg;
+       /* if not NULL, set *flag to val when option found */
+       int *flag;
+       /* if flag not NULL, value to set *flag to; else return value */
+       int val;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int     getopt_long(int, char * const *, const char *,
+           const struct option *, int *);
+int     getopt_long_only(int, char * const *, const char *,
+           const struct option *, int *);
+#ifndef _GETOPT_DEFINED
+#define _GETOPT_DEFINED
+int     getopt(int, char * const *, const char *);
+int     getsubopt(char **, char * const *, char **);
+
+extern   char *optarg;                  /* getopt(3) external variables */
+extern   int opterr;
+extern   int optind;
+extern   int optopt;
+extern   int optreset;
+extern   char *suboptarg;               /* getsubopt(3) external variable */
+#endif /* _GETOPT_DEFINED */
+#ifdef __cplusplus
+}
+#endif
+#endif /* !_GETOPT_H_ */
+/*     $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $        */
+/*     $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $    */
+/*     $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $      */
+
+/*
+ * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+
+#ifndef lint
+static const char rcsid[]="$Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $";
+#endif /* lint */
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+// Define this to replace system getopt
+//
+//#define      REPLACE_GETOPT          /* use this getopt as the system getopt(3) */
+
+#ifdef REPLACE_GETOPT
+int    opterr = 1;             /* if error message should be printed */
+int    optind = 1;             /* index into parent argv vector */
+int    optopt = '?';           /* character checked for validity */
+int    optreset;               /* reset getopt */
+char    *optarg;               /* argument associated with option */
+
+
+#define PRINT_ERROR    ((opterr) && (*options != ':'))
+
+#define FLAG_PERMUTE   0x01    /* permute non-options to the end of argv */
+#define FLAG_ALLARGS   0x02    /* treat non-options as args to option "-1" */
+#define FLAG_LONGONLY  0x04    /* operate as getopt_long_only */
+
+/* return values */
+#define        BADCH           (int)'?'
+#define        BADARG          ((*options == ':') ? (int)':' : (int)'?')
+#define        INORDER         (int)1
+
+#define        EMSG            ""
+
+static int getopt_internal(int, char * const *, const char *,
+                          const struct option *, int *, int);
+static int parse_long_options(char * const *, const char *,
+                             const struct option *, int *, int);
+static int gcd(int, int);
+static void permute_args(int, int, int, char * const *);
+
+static char *place = EMSG; /* option letter processing */
+
+/* XXX: set optreset to 1 rather than these two */
+static int nonopt_start = -1; /* first non option argument (for permute) */
+static int nonopt_end = -1;   /* first option after non options (for permute) */
+
+/* Error messages */
+static const char recargchar[] = "option requires an argument -- %c";
+static const char recargstring[] = "option requires an argument -- %s";
+static const char ambig[] = "ambiguous option -- %.*s";
+static const char noarg[] = "option doesn't take an argument -- %.*s";
+static const char illoptchar[] = "unknown option -- %c";
+static const char illoptstring[] = "unknown option -- %s";
+
+
+#if defined(_WIN32) || defined(ESP_PLATFORM)
+
+/* Windows needs warnx().  We change the definition though:
+ *  1. (another) global is defined, opterrmsg, which holds the error message
+ *  2. errors are always printed out on stderr w/o the program name
+ * Note that opterrmsg always gets set no matter what opterr is set to.  The
+ * error message will not be printed if opterr is 0 as usual.
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+
+extern char opterrmsg[128];
+char opterrmsg[128]; /* buffer for the last error message */
+
+static void warnx(const char *fmt, ...)
+{
+       va_list ap;
+       va_start(ap, fmt);
+    /*
+    Make sure opterrmsg is always zero-terminated despite the _vsnprintf()
+    implementation specifics and manually suppress the warning.
+    */
+    memset(opterrmsg, 0, sizeof opterrmsg);
+       if (fmt != NULL)
+               vsnprintf(opterrmsg, sizeof(opterrmsg) - 1, fmt, ap);
+       va_end(ap);
+#if defined(_WIN32)
+#pragma warning(suppress: 6053)
+#endif
+       fprintf(stderr, "%s\n", opterrmsg);
+}
+
+#else
+#include <err.h>
+#endif /*_WIN32*/
+
+/*
+ * Compute the greatest common divisor of a and b.
+ */
+static int
+gcd(int a, int b)
+{
+       int c;
+
+       c = a % b;
+       while (c != 0) {
+               a = b;
+               b = c;
+               c = a % b;
+       }
+
+       return (b);
+}
+
+/*
+ * Exchange the block from nonopt_start to nonopt_end with the block
+ * from nonopt_end to opt_end (keeping the same order of arguments
+ * in each block).
+ */
+static void
+permute_args(int panonopt_start, int panonopt_end, int opt_end,
+       char * const *nargv)
+{
+       int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
+       char *swap;
+
+       /*
+        * compute lengths of blocks and number and size of cycles
+        */
+       nnonopts = panonopt_end - panonopt_start;
+       nopts = opt_end - panonopt_end;
+       ncycle = gcd(nnonopts, nopts);
+       cyclelen = (opt_end - panonopt_start) / ncycle;
+
+       for (i = 0; i < ncycle; i++) {
+               cstart = panonopt_end+i;
+               pos = cstart;
+               for (j = 0; j < cyclelen; j++) {
+                       if (pos >= panonopt_end)
+                               pos -= nnonopts;
+                       else
+                               pos += nopts;
+                       swap = nargv[pos];
+                       /* LINTED const cast */
+                       ((char **) nargv)[pos] = nargv[cstart];
+                       /* LINTED const cast */
+                       ((char **)nargv)[cstart] = swap;
+               }
+       }
+}
+
+/*
+ * parse_long_options --
+ *     Parse long options in argc/argv argument vector.
+ * Returns -1 if short_too is set and the option does not match long_options.
+ */
+static int
+parse_long_options(char * const *nargv, const char *options,
+       const struct option *long_options, int *idx, int short_too)
+{
+       char *current_argv, *has_equal;
+       size_t current_argv_len;
+       int i, match;
+
+       current_argv = place;
+       match = -1;
+
+       optind++;
+
+       if ((has_equal = strchr(current_argv, '=')) != NULL) {
+               /* argument found (--option=arg) */
+               current_argv_len = has_equal - current_argv;
+               has_equal++;
+       } else
+               current_argv_len = strlen(current_argv);
+
+       for (i = 0; long_options[i].name; i++) {
+               /* find matching long option */
+               if (strncmp(current_argv, long_options[i].name,
+                   current_argv_len))
+                       continue;
+
+               if (strlen(long_options[i].name) == current_argv_len) {
+                       /* exact match */
+                       match = i;
+                       break;
+               }
+               /*
+                * If this is a known short option, don't allow
+                * a partial match of a single character.
+                */
+               if (short_too && current_argv_len == 1)
+                       continue;
+
+               if (match == -1)        /* partial match */
+                       match = i;
+               else {
+                       /* ambiguous abbreviation */
+                       if (PRINT_ERROR)
+                               warnx(ambig, (int)current_argv_len,
+                                    current_argv);
+                       optopt = 0;
+                       return (BADCH);
+               }
+       }
+       if (match != -1) {              /* option found */
+               if (long_options[match].has_arg == no_argument
+                   && has_equal) {
+                       if (PRINT_ERROR)
+                               warnx(noarg, (int)current_argv_len,
+                                    current_argv);
+                       /*
+                        * XXX: GNU sets optopt to val regardless of flag
+                        */
+                       if (long_options[match].flag == NULL)
+                               optopt = long_options[match].val;
+                       else
+                               optopt = 0;
+                       return (BADARG);
+               }
+               if (long_options[match].has_arg == required_argument ||
+                   long_options[match].has_arg == optional_argument) {
+                       if (has_equal)
+                               optarg = has_equal;
+                       else if (long_options[match].has_arg ==
+                           required_argument) {
+                               /*
+                                * optional argument doesn't use next nargv
+                                */
+                               optarg = nargv[optind++];
+                       }
+               }
+               if ((long_options[match].has_arg == required_argument)
+                   && (optarg == NULL)) {
+                       /*
+                        * Missing argument; leading ':' indicates no error
+                        * should be generated.
+                        */
+                       if (PRINT_ERROR)
+                               warnx(recargstring,
+                                   current_argv);
+                       /*
+                        * XXX: GNU sets optopt to val regardless of flag
+                        */
+                       if (long_options[match].flag == NULL)
+                               optopt = long_options[match].val;
+                       else
+                               optopt = 0;
+                       --optind;
+                       return (BADARG);
+               }
+       } else {                        /* unknown option */
+               if (short_too) {
+                       --optind;
+                       return (-1);
+               }
+               if (PRINT_ERROR)
+                       warnx(illoptstring, current_argv);
+               optopt = 0;
+               return (BADCH);
+       }
+       if (idx)
+               *idx = match;
+       if (long_options[match].flag) {
+               *long_options[match].flag = long_options[match].val;
+               return (0);
+       } else
+               return (long_options[match].val);
+}
+
+/*
+ * getopt_internal --
+ *     Parse argc/argv argument vector.  Called by user level routines.
+ */
+static int
+getopt_internal(int nargc, char * const *nargv, const char *options,
+       const struct option *long_options, int *idx, int flags)
+{
+       char *oli;                              /* option letter list index */
+       int optchar, short_too;
+       static int posixly_correct = -1;
+
+       if (options == NULL)
+               return (-1);
+
+       /*
+        * Disable GNU extensions if POSIXLY_CORRECT is set or options
+        * string begins with a '+'.
+        */
+       if (posixly_correct == -1)
+               posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
+       if (posixly_correct || *options == '+')
+               flags &= ~FLAG_PERMUTE;
+       else if (*options == '-')
+               flags |= FLAG_ALLARGS;
+       if (*options == '+' || *options == '-')
+               options++;
+
+       /*
+        * XXX Some GNU programs (like cvs) set optind to 0 instead of
+        * XXX using optreset.  Work around this braindamage.
+        */
+       if (optind == 0)
+               optind = optreset = 1;
+
+       optarg = NULL;
+       if (optreset)
+               nonopt_start = nonopt_end = -1;
+start:
+       if (optreset || !*place) {              /* update scanning pointer */
+               optreset = 0;
+               if (optind >= nargc) {          /* end of argument vector */
+                       place = EMSG;
+                       if (nonopt_end != -1) {
+                               /* do permutation, if we have to */
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, nargv);
+                               optind -= nonopt_end - nonopt_start;
+                       }
+                       else if (nonopt_start != -1) {
+                               /*
+                                * If we skipped non-options, set optind
+                                * to the first of them.
+                                */
+                               optind = nonopt_start;
+                       }
+                       nonopt_start = nonopt_end = -1;
+                       return (-1);
+               }
+               if (*(place = nargv[optind]) != '-' ||
+                   (place[1] == '\0' && strchr(options, '-') == NULL)) {
+                       place = EMSG;           /* found non-option */
+                       if (flags & FLAG_ALLARGS) {
+                               /*
+                                * GNU extension:
+                                * return non-option as argument to option 1
+                                */
+                               optarg = nargv[optind++];
+                               return (INORDER);
+                       }
+                       if (!(flags & FLAG_PERMUTE)) {
+                               /*
+                                * If no permutation wanted, stop parsing
+                                * at first non-option.
+                                */
+                               return (-1);
+                       }
+                       /* do permutation */
+                       if (nonopt_start == -1)
+                               nonopt_start = optind;
+                       else if (nonopt_end != -1) {
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, nargv);
+                               nonopt_start = optind -
+                                   (nonopt_end - nonopt_start);
+                               nonopt_end = -1;
+                       }
+                       optind++;
+                       /* process next argument */
+                       goto start;
+               }
+               if (nonopt_start != -1 && nonopt_end == -1)
+                       nonopt_end = optind;
+
+               /*
+                * If we have "-" do nothing, if "--" we are done.
+                */
+               if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
+                       optind++;
+                       place = EMSG;
+                       /*
+                        * We found an option (--), so if we skipped
+                        * non-options, we have to permute.
+                        */
+                       if (nonopt_end != -1) {
+                               permute_args(nonopt_start, nonopt_end,
+                                   optind, nargv);
+                               optind -= nonopt_end - nonopt_start;
+                       }
+                       nonopt_start = nonopt_end = -1;
+                       return (-1);
+               }
+       }
+
+       /*
+        * Check long options if:
+        *  1) we were passed some
+        *  2) the arg is not just "-"
+        *  3) either the arg starts with -- we are getopt_long_only()
+        */
+       if (long_options != NULL && place != nargv[optind] &&
+           (*place == '-' || (flags & FLAG_LONGONLY))) {
+               short_too = 0;
+               if (*place == '-')
+                       place++;                /* --foo long option */
+               else if (*place != ':' && strchr(options, *place) != NULL)
+                       short_too = 1;          /* could be short option too */
+
+               optchar = parse_long_options(nargv, options, long_options,
+                   idx, short_too);
+               if (optchar != -1) {
+                       place = EMSG;
+                       return (optchar);
+               }
+       }
+
+       if ((optchar = (int)*place++) == (int)':' ||
+           (optchar == (int)'-' && *place != '\0') ||
+           (oli = strchr(options, optchar)) == NULL) {
+               /*
+                * If the user specified "-" and  '-' isn't listed in
+                * options, return -1 (non-option) as per POSIX.
+                * Otherwise, it is an unknown option character (or ':').
+                */
+               if (optchar == (int)'-' && *place == '\0')
+                       return (-1);
+               if (!*place)
+                       ++optind;
+               if (PRINT_ERROR)
+                       warnx(illoptchar, optchar);
+               optopt = optchar;
+               return (BADCH);
+       }
+       if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
+               /* -W long-option */
+               if (*place)                     /* no space */
+                       /* NOTHING */;
+               else if (++optind >= nargc) {   /* no arg */
+                       place = EMSG;
+                       if (PRINT_ERROR)
+                               warnx(recargchar, optchar);
+                       optopt = optchar;
+                       return (BADARG);
+               } else                          /* white space */
+                       place = nargv[optind];
+               optchar = parse_long_options(nargv, options, long_options,
+                   idx, 0);
+               place = EMSG;
+               return (optchar);
+       }
+       if (*++oli != ':') {                    /* doesn't take argument */
+               if (!*place)
+                       ++optind;
+       } else {                                /* takes (optional) argument */
+               optarg = NULL;
+               if (*place)                     /* no white space */
+                       optarg = place;
+               else if (oli[1] != ':') {       /* arg not optional */
+                       if (++optind >= nargc) {        /* no arg */
+                               place = EMSG;
+                               if (PRINT_ERROR)
+                                       warnx(recargchar, optchar);
+                               optopt = optchar;
+                               return (BADARG);
+                       } else
+                               optarg = nargv[optind];
+               }
+               place = EMSG;
+               ++optind;
+       }
+       /* dump back option letter */
+       return (optchar);
+}
+
+
+/*
+ * getopt --
+ *     Parse argc/argv argument vector.
+ *
+ * [eventually this will replace the BSD getopt]
+ */
+int
+getopt(int nargc, char * const *nargv, const char *options)
+{
+
+       /*
+        * We don't pass FLAG_PERMUTE to getopt_internal() since
+        * the BSD getopt(3) (unlike GNU) has never done this.
+        *
+        * Furthermore, since many privileged programs call getopt()
+        * before dropping privileges it makes sense to keep things
+        * as simple (and bug-free) as possible.
+        */
+       return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
+}
+
+
+/*
+ * getopt_long --
+ *     Parse argc/argv argument vector.
+ */
+int
+getopt_long(int nargc, char * const *nargv, const char *options,
+    const struct option *long_options, int *idx)
+{
+
+       return (getopt_internal(nargc, nargv, options, long_options, idx,
+           FLAG_PERMUTE));
+}
+
+/*
+ * getopt_long_only --
+ *     Parse argc/argv argument vector.
+ */
+int
+getopt_long_only(int nargc, char * const *nargv, const char *options,
+    const struct option *long_options, int *idx)
+{
+
+       return (getopt_internal(nargc, nargv, options, long_options, idx,
+           FLAG_PERMUTE|FLAG_LONGONLY));
+}
+#endif /* REPLACE_GETOPT */
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "argtable3.h"
+
+
+char * arg_strptime(const char *buf, const char *fmt, struct tm *tm);
+
+
+static void arg_date_resetfn(struct arg_date *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+static int arg_date_scanfn(struct arg_date *parent, const char *argval)
+{
+    int errorcode = 0;
+
+    if (parent->count == parent->hdr.maxcount)
+    {
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* no argument value was given, leave parent->tmval[] unaltered but still count it */
+        parent->count++;
+    }
+    else
+    {
+        const char *pend;
+        struct tm tm = parent->tmval[parent->count];
+
+        /* parse the given argument value, store result in parent->tmval[] */
+        pend = arg_strptime(argval, parent->format, &tm);
+        if (pend && pend[0] == '\0')
+            parent->tmval[parent->count++] = tm;
+        else
+            errorcode = EBADDATE;
+    }
+
+    ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static int arg_date_checkfn(struct arg_date *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+
+    ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static void arg_date_errorfn(
+    struct arg_date *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    case EBADDATE:
+    {
+        struct tm tm;
+        char buff[200];
+
+        fprintf(fp, "illegal timestamp format \"%s\"\n", argval);
+        memset(&tm, 0, sizeof(tm));
+        arg_strptime("1999-12-31 23:59:59", "%F %H:%M:%S", &tm);
+        strftime(buff, sizeof(buff), parent->format, &tm);
+        printf("correct format is \"%s\"\n", buff);
+        break;
+    }
+    }
+}
+
+
+struct arg_date * arg_date0(
+    const char * shortopts,
+    const char * longopts,
+    const char * format,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_daten(shortopts, longopts, format, datatype, 0, 1, glossary);
+}
+
+
+struct arg_date * arg_date1(
+    const char * shortopts,
+    const char * longopts,
+    const char * format,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_daten(shortopts, longopts, format, datatype, 1, 1, glossary);
+}
+
+
+struct arg_date * arg_daten(
+    const char * shortopts,
+    const char * longopts,
+    const char * format,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    size_t nbytes;
+    struct arg_date *result;
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    /* default time format is the national date format for the locale */
+    if (!format)
+        format = "%x";
+
+    nbytes = sizeof(struct arg_date)         /* storage for struct arg_date */
+        + maxcount * sizeof(struct tm);    /* storage for tmval[maxcount] array */
+
+    /* allocate storage for the arg_date struct + tmval[] array.    */
+    /* we use calloc because we want the tmval[] array zero filled. */
+    result = (struct arg_date *)calloc(1, nbytes);
+    if (result)
+    {
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_HASVALUE;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.datatype  = datatype ? datatype : format;
+        result->hdr.glossary  = glossary;
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_date_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_date_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_date_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_date_errorfn;
+
+        /* store the tmval[maxcount] array immediately after the arg_date struct */
+        result->tmval  = (struct tm *)(result + 1);
+
+        /* init the remaining arg_date member variables */
+        result->count = 0;
+        result->format = format;
+    }
+
+    ARG_TRACE(("arg_daten() returns %p\n", result));
+    return result;
+}
+
+
+/*-
+ * Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code was contributed to The NetBSD Foundation by Klaus Klein.
+ * Heavily optimised by David Laight
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <ctype.h>
+#include <string.h>
+#include <time.h>
+
+/*
+ * We do not implement alternate representations. However, we always
+ * check whether a given modifier is allowed for a certain conversion.
+ */
+#define ALT_E                   0x01
+#define ALT_O                   0x02
+#define LEGAL_ALT(x)            { if (alt_format & ~(x)) return (0); }
+#define TM_YEAR_BASE   (1900)
+
+static int conv_num(const char * *, int *, int, int);
+
+static const char *day[7] = {
+    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
+    "Friday", "Saturday"
+};
+
+static const char *abday[7] = {
+    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+};
+
+static const char *mon[12] = {
+    "January", "February", "March", "April", "May", "June", "July",
+    "August", "September", "October", "November", "December"
+};
+
+static const char *abmon[12] = {
+    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+};
+
+static const char *am_pm[2] = {
+    "AM", "PM"
+};
+
+
+static int arg_strcasecmp(const char *s1, const char *s2)
+{
+    const unsigned char *us1 = (const unsigned char *)s1;
+    const unsigned char *us2 = (const unsigned char *)s2;
+    while (tolower(*us1) == tolower(*us2++))
+        if (*us1++ == '\0')
+            return 0;
+
+    return tolower(*us1) - tolower(*--us2);
+}
+
+
+static int arg_strncasecmp(const char *s1, const char *s2, size_t n)
+{
+    if (n != 0)
+    {
+        const unsigned char *us1 = (const unsigned char *)s1;
+        const unsigned char *us2 = (const unsigned char *)s2;
+        do
+        {
+            if (tolower(*us1) != tolower(*us2++))
+                return tolower(*us1) - tolower(*--us2);
+
+            if (*us1++ == '\0')
+                break;
+        } while (--n != 0);
+    }
+
+    return 0;
+}
+
+
+char * arg_strptime(const char *buf, const char *fmt, struct tm *tm)
+{
+    char c;
+    const char *bp;
+    size_t len = 0;
+    int alt_format, i, split_year = 0;
+
+    bp = buf;
+
+    while ((c = *fmt) != '\0') {
+        /* Clear `alternate' modifier prior to new conversion. */
+        alt_format = 0;
+
+        /* Eat up white-space. */
+        if (isspace(c)) {
+            while (isspace(*bp))
+                bp++;
+
+            fmt++;
+            continue;
+        }
+
+        if ((c = *fmt++) != '%')
+            goto literal;
+
+
+again:
+        switch (c = *fmt++)
+        {
+        case '%': /* "%%" is converted to "%". */
+literal:
+            if (c != *bp++)
+                return (0);
+            break;
+
+        /*
+         * "Alternative" modifiers. Just set the appropriate flag
+         * and start over again.
+         */
+        case 'E': /* "%E?" alternative conversion modifier. */
+            LEGAL_ALT(0);
+            alt_format |= ALT_E;
+            goto again;
+
+        case 'O': /* "%O?" alternative conversion modifier. */
+            LEGAL_ALT(0);
+            alt_format |= ALT_O;
+            goto again;
+
+        /*
+         * "Complex" conversion rules, implemented through recursion.
+         */
+        case 'c': /* Date and time, using the locale's format. */
+            LEGAL_ALT(ALT_E);
+            bp = arg_strptime(bp, "%x %X", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'D': /* The date as "%m/%d/%y". */
+            LEGAL_ALT(0);
+            bp = arg_strptime(bp, "%m/%d/%y", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'R': /* The time as "%H:%M". */
+            LEGAL_ALT(0);
+            bp = arg_strptime(bp, "%H:%M", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'r': /* The time in 12-hour clock representation. */
+            LEGAL_ALT(0);
+            bp = arg_strptime(bp, "%I:%M:%S %p", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'T': /* The time as "%H:%M:%S". */
+            LEGAL_ALT(0);
+            bp = arg_strptime(bp, "%H:%M:%S", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'X': /* The time, using the locale's format. */
+            LEGAL_ALT(ALT_E);
+            bp = arg_strptime(bp, "%H:%M:%S", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        case 'x': /* The date, using the locale's format. */
+            LEGAL_ALT(ALT_E);
+            bp = arg_strptime(bp, "%m/%d/%y", tm);
+            if (!bp)
+                return (0);
+            break;
+
+        /*
+         * "Elementary" conversion rules.
+         */
+        case 'A': /* The day of week, using the locale's form. */
+        case 'a':
+            LEGAL_ALT(0);
+            for (i = 0; i < 7; i++) {
+                /* Full name. */
+                len = strlen(day[i]);
+                if (arg_strncasecmp(day[i], bp, len) == 0)
+                    break;
+
+                /* Abbreviated name. */
+                len = strlen(abday[i]);
+                if (arg_strncasecmp(abday[i], bp, len) == 0)
+                    break;
+            }
+
+            /* Nothing matched. */
+            if (i == 7)
+                return (0);
+
+            tm->tm_wday = i;
+            bp += len;
+            break;
+
+        case 'B': /* The month, using the locale's form. */
+        case 'b':
+        case 'h':
+            LEGAL_ALT(0);
+            for (i = 0; i < 12; i++) {
+                /* Full name. */
+                len = strlen(mon[i]);
+                if (arg_strncasecmp(mon[i], bp, len) == 0)
+                    break;
+
+                /* Abbreviated name. */
+                len = strlen(abmon[i]);
+                if (arg_strncasecmp(abmon[i], bp, len) == 0)
+                    break;
+            }
+
+            /* Nothing matched. */
+            if (i == 12)
+                return (0);
+
+            tm->tm_mon = i;
+            bp += len;
+            break;
+
+        case 'C': /* The century number. */
+            LEGAL_ALT(ALT_E);
+            if (!(conv_num(&bp, &i, 0, 99)))
+                return (0);
+
+            if (split_year) {
+                tm->tm_year = (tm->tm_year % 100) + (i * 100);
+            } else {
+                tm->tm_year = i * 100;
+                split_year = 1;
+            }
+            break;
+
+        case 'd': /* The day of month. */
+        case 'e':
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_mday, 1, 31)))
+                return (0);
+            break;
+
+        case 'k': /* The hour (24-hour clock representation). */
+            LEGAL_ALT(0);
+        /* FALLTHROUGH */
+        case 'H':
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_hour, 0, 23)))
+                return (0);
+            break;
+
+        case 'l': /* The hour (12-hour clock representation). */
+            LEGAL_ALT(0);
+        /* FALLTHROUGH */
+        case 'I':
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_hour, 1, 12)))
+                return (0);
+            if (tm->tm_hour == 12)
+                tm->tm_hour = 0;
+            break;
+
+        case 'j': /* The day of year. */
+            LEGAL_ALT(0);
+            if (!(conv_num(&bp, &i, 1, 366)))
+                return (0);
+            tm->tm_yday = i - 1;
+            break;
+
+        case 'M': /* The minute. */
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_min, 0, 59)))
+                return (0);
+            break;
+
+        case 'm': /* The month. */
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &i, 1, 12)))
+                return (0);
+            tm->tm_mon = i - 1;
+            break;
+
+        case 'p': /* The locale's equivalent of AM/PM. */
+            LEGAL_ALT(0);
+            /* AM? */
+            if (arg_strcasecmp(am_pm[0], bp) == 0) {
+                if (tm->tm_hour > 11)
+                    return (0);
+
+                bp += strlen(am_pm[0]);
+                break;
+            }
+            /* PM? */
+            else if (arg_strcasecmp(am_pm[1], bp) == 0) {
+                if (tm->tm_hour > 11)
+                    return (0);
+
+                tm->tm_hour += 12;
+                bp += strlen(am_pm[1]);
+                break;
+            }
+
+            /* Nothing matched. */
+            return (0);
+
+        case 'S': /* The seconds. */
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_sec, 0, 61)))
+                return (0);
+            break;
+
+        case 'U': /* The week of year, beginning on sunday. */
+        case 'W': /* The week of year, beginning on monday. */
+            LEGAL_ALT(ALT_O);
+            /*
+             * XXX This is bogus, as we can not assume any valid
+             * information present in the tm structure at this
+             * point to calculate a real value, so just check the
+             * range for now.
+             */
+            if (!(conv_num(&bp, &i, 0, 53)))
+                return (0);
+            break;
+
+        case 'w': /* The day of week, beginning on sunday. */
+            LEGAL_ALT(ALT_O);
+            if (!(conv_num(&bp, &tm->tm_wday, 0, 6)))
+                return (0);
+            break;
+
+        case 'Y': /* The year. */
+            LEGAL_ALT(ALT_E);
+            if (!(conv_num(&bp, &i, 0, 9999)))
+                return (0);
+
+            tm->tm_year = i - TM_YEAR_BASE;
+            break;
+
+        case 'y': /* The year within 100 years of the epoch. */
+            LEGAL_ALT(ALT_E | ALT_O);
+            if (!(conv_num(&bp, &i, 0, 99)))
+                return (0);
+
+            if (split_year) {
+                tm->tm_year = ((tm->tm_year / 100) * 100) + i;
+                break;
+            }
+            split_year = 1;
+            if (i <= 68)
+                tm->tm_year = i + 2000 - TM_YEAR_BASE;
+            else
+                tm->tm_year = i + 1900 - TM_YEAR_BASE;
+            break;
+
+        /*
+         * Miscellaneous conversions.
+         */
+        case 'n': /* Any kind of white-space. */
+        case 't':
+            LEGAL_ALT(0);
+            while (isspace(*bp))
+                bp++;
+            break;
+
+
+        default: /* Unknown/unsupported conversion. */
+            return (0);
+        }
+
+
+    }
+
+    /* LINTED functional specification */
+    return ((char *)bp);
+}
+
+
+static int conv_num(const char * *buf, int *dest, int llim, int ulim)
+{
+    int result = 0;
+
+    /* The limit also determines the number of valid digits. */
+    int rulim = ulim;
+
+    if (**buf < '0' || **buf > '9')
+        return (0);
+
+    do {
+        result *= 10;
+        result += *(*buf)++ - '0';
+        rulim /= 10;
+    } while ((result * 10 <= ulim) && rulim && **buf >= '0' && **buf <= '9');
+
+    if (result < llim || result > ulim)
+        return (0);
+
+    *dest = result;
+    return (1);
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+
+static void arg_dbl_resetfn(struct arg_dbl *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval)
+{
+    int errorcode = 0;
+
+    if (parent->count == parent->hdr.maxcount)
+    {
+        /* maximum number of arguments exceeded */
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* a valid argument with no argument value was given. */
+        /* This happens when an optional argument value was invoked. */
+        /* leave parent argument value unaltered but still count the argument. */
+        parent->count++;
+    }
+    else
+    {
+        double val;
+        char *end;
+
+        /* extract double from argval into val */
+        val = strtod(argval, &end);
+
+        /* if success then store result in parent->dval[] array otherwise return error*/
+        if (*end == 0)
+            parent->dval[parent->count++] = val;
+        else
+            errorcode = EBADDOUBLE;
+    }
+
+    ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static int arg_dbl_checkfn(struct arg_dbl *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    
+    ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static void arg_dbl_errorfn(
+    struct arg_dbl *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    case EBADDOUBLE:
+        fprintf(fp, "invalid argument \"%s\" to option ", argval);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+    }
+}
+
+
+struct arg_dbl * arg_dbl0(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_dbln(shortopts, longopts, datatype, 0, 1, glossary);
+}
+
+
+struct arg_dbl * arg_dbl1(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_dbln(shortopts, longopts, datatype, 1, 1, glossary);
+}
+
+
+struct arg_dbl * arg_dbln(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    size_t nbytes;
+    struct arg_dbl *result;
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    nbytes = sizeof(struct arg_dbl)     /* storage for struct arg_dbl */
+             + (maxcount + 1) * sizeof(double); /* storage for dval[maxcount] array plus one extra for padding to memory boundary */
+
+    result = (struct arg_dbl *)malloc(nbytes);
+    if (result)
+    {
+        size_t addr;
+        size_t rem;
+
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_HASVALUE;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.datatype  = datatype ? datatype : "<double>";
+        result->hdr.glossary  = glossary;
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_dbl_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_dbl_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_dbl_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_dbl_errorfn;
+
+        /* Store the dval[maxcount] array on the first double boundary that
+         * immediately follows the arg_dbl struct. We do the memory alignment
+         * purely for SPARC and Motorola systems. They require floats and
+         * doubles to be aligned on natural boundaries.
+         */
+        addr = (size_t)(result + 1);
+        rem  = addr % sizeof(double);
+        result->dval  = (double *)(addr + sizeof(double) - rem);
+        ARG_TRACE(("addr=%p, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
+
+        result->count = 0;
+    }
+    
+    ARG_TRACE(("arg_dbln() returns %p\n", result));
+    return result;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+
+static void arg_end_resetfn(struct arg_end *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+static void arg_end_errorfn(
+    void *parent,
+    FILE *fp,
+    int error,
+    const char *argval,
+    const char *progname)
+{
+    /* suppress unreferenced formal parameter warning */
+    (void)parent;
+
+    progname = progname ? progname : "";
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(error)
+    {
+    case ARG_ELIMIT:
+        fputs("too many errors to display", fp);
+        break;
+    case ARG_EMALLOC:
+        fputs("insufficent memory", fp);
+        break;
+    case ARG_ENOMATCH:
+        fprintf(fp, "unexpected argument \"%s\"", argval);
+        break;
+    case ARG_EMISSARG:
+        fprintf(fp, "option \"%s\" requires an argument", argval);
+        break;
+    case ARG_ELONGOPT:
+        fprintf(fp, "invalid option \"%s\"", argval);
+        break;
+    default:
+        fprintf(fp, "invalid option \"-%c\"", error);
+        break;
+    }
+    
+    fputc('\n', fp);
+}
+
+
+struct arg_end * arg_end(int maxcount)
+{
+    size_t nbytes;
+    struct arg_end *result;
+
+    nbytes = sizeof(struct arg_end)
+             + maxcount * sizeof(int)     /* storage for int error[maxcount] array*/
+             + maxcount * sizeof(void *)  /* storage for void* parent[maxcount] array */
+             + maxcount * sizeof(char *); /* storage for char* argval[maxcount] array */
+
+    result = (struct arg_end *)malloc(nbytes);
+    if (result)
+    {
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_TERMINATOR;
+        result->hdr.shortopts = NULL;
+        result->hdr.longopts  = NULL;
+        result->hdr.datatype  = NULL;
+        result->hdr.glossary  = NULL;
+        result->hdr.mincount  = 1;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_end_resetfn;
+        result->hdr.scanfn    = NULL;
+        result->hdr.checkfn   = NULL;
+        result->hdr.errorfn   = (arg_errorfn *)arg_end_errorfn;
+
+        /* store error[maxcount] array immediately after struct arg_end */
+        result->error = (int *)(result + 1);
+
+        /* store parent[maxcount] array immediately after error[] array */
+        result->parent = (void * *)(result->error + maxcount );
+
+        /* store argval[maxcount] array immediately after parent[] array */
+        result->argval = (const char * *)(result->parent + maxcount );
+    }
+
+    ARG_TRACE(("arg_end(%d) returns %p\n", maxcount, result));
+    return result;
+}
+
+
+void arg_print_errors(FILE * fp, struct arg_end * end, const char * progname)
+{
+    int i;
+    ARG_TRACE(("arg_errors()\n"));
+    for (i = 0; i < end->count; i++)
+    {
+        struct arg_hdr *errorparent = (struct arg_hdr *)(end->parent[i]);
+        if (errorparent->errorfn)
+            errorparent->errorfn(end->parent[i],
+                                 fp,
+                                 end->error[i],
+                                 end->argval[i],
+                                 progname);
+    }
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <string.h>
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+#ifdef WIN32
+# define FILESEPARATOR1 '\\'
+# define FILESEPARATOR2 '/'
+#else
+# define FILESEPARATOR1 '/'
+# define FILESEPARATOR2 '/'
+#endif
+
+
+static void arg_file_resetfn(struct arg_file *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+/* Returns ptr to the base filename within *filename */
+static const char * arg_basename(const char *filename)
+{
+    const char *result = NULL, *result1, *result2;
+
+    /* Find the last occurrence of eother file separator character. */
+    /* Two alternative file separator chars are supported as legal  */
+    /* file separators but not both together in the same filename.  */
+    result1 = (filename ? strrchr(filename, FILESEPARATOR1) : NULL);
+    result2 = (filename ? strrchr(filename, FILESEPARATOR2) : NULL);
+
+    if (result2)
+        result = result2 + 1;  /* using FILESEPARATOR2 (the alternative file separator) */
+
+    if (result1)
+        result = result1 + 1;  /* using FILESEPARATOR1 (the preferred file separator) */
+
+    if (!result)
+        result = filename;  /* neither file separator was found so basename is the whole filename */
+
+    /* special cases of "." and ".." are not considered basenames */
+    if (result && ( strcmp(".", result) == 0 || strcmp("..", result) == 0 ))
+        result = filename + strlen(filename);
+
+    return result;
+}
+
+
+/* Returns ptr to the file extension within *basename */
+static const char * arg_extension(const char *basename)
+{
+    /* find the last occurrence of '.' in basename */
+    const char *result = (basename ? strrchr(basename, '.') : NULL);
+
+    /* if no '.' was found then return pointer to end of basename */
+    if (basename && !result)
+        result = basename + strlen(basename);
+
+    /* special case: basenames with a single leading dot (eg ".foo") are not considered as true extensions */
+    if (basename && result == basename)
+        result = basename + strlen(basename);
+
+    /* special case: empty extensions (eg "foo.","foo..") are not considered as true extensions */
+    if (basename && result && result[1] == '\0')
+        result = basename + strlen(basename);
+
+    return result;
+}
+
+
+static int arg_file_scanfn(struct arg_file *parent, const char *argval)
+{
+    int errorcode = 0;
+
+    if (parent->count == parent->hdr.maxcount)
+    {
+        /* maximum number of arguments exceeded */
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* a valid argument with no argument value was given. */
+        /* This happens when an optional argument value was invoked. */
+        /* leave parent arguiment value unaltered but still count the argument. */
+        parent->count++;
+    }
+    else
+    {
+        parent->filename[parent->count]  = argval;
+        parent->basename[parent->count]  = arg_basename(argval);
+        parent->extension[parent->count] =
+            arg_extension(parent->basename[parent->count]);                                /* only seek extensions within the basename (not the file path)*/
+        parent->count++;
+    }
+
+    ARG_TRACE(("%s4:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static int arg_file_checkfn(struct arg_file *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    
+    ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static void arg_file_errorfn(
+    struct arg_file *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    default:
+        fprintf(fp, "unknown error at \"%s\"\n", argval);
+    }
+}
+
+
+struct arg_file * arg_file0(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_filen(shortopts, longopts, datatype, 0, 1, glossary);
+}
+
+
+struct arg_file * arg_file1(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_filen(shortopts, longopts, datatype, 1, 1, glossary);
+}
+
+
+struct arg_file * arg_filen(
+    const char * shortopts,
+    const char * longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    size_t nbytes;
+    struct arg_file *result;
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    nbytes = sizeof(struct arg_file)      /* storage for struct arg_file */
+             + sizeof(char *) * maxcount  /* storage for filename[maxcount] array */
+             + sizeof(char *) * maxcount  /* storage for basename[maxcount] array */
+             + sizeof(char *) * maxcount; /* storage for extension[maxcount] array */
+
+    result = (struct arg_file *)malloc(nbytes);
+    if (result)
+    {
+        int i;
+
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_HASVALUE;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.glossary  = glossary;
+        result->hdr.datatype  = datatype ? datatype : "<file>";
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_file_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_file_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_file_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_file_errorfn;
+
+        /* store the filename,basename,extension arrays immediately after the arg_file struct */
+        result->filename  = (const char * *)(result + 1);
+        result->basename  = result->filename + maxcount;
+        result->extension = result->basename + maxcount;
+        result->count = 0;
+
+        /* foolproof the string pointers by initialising them with empty strings */
+        for (i = 0; i < maxcount; i++)
+        {
+            result->filename[i] = "";
+            result->basename[i] = "";
+            result->extension[i] = "";
+        }
+    }
+    
+    ARG_TRACE(("arg_filen() returns %p\n", result));
+    return result;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+#include <limits.h>
+#include <ctype.h>
+
+#include "argtable3.h"
+
+
+static void arg_int_resetfn(struct arg_int *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+/* strtol0x() is like strtol() except that the numeric string is    */
+/* expected to be prefixed by "0X" where X is a user supplied char. */
+/* The string may optionally be prefixed by white space and + or -  */
+/* as in +0X123 or -0X123.                                          */
+/* Once the prefix has been scanned, the remainder of the numeric   */
+/* string is converted using strtol() with the given base.          */
+/* eg: to parse hex str="-0X12324", specify X='X' and base=16.      */
+/* eg: to parse oct str="+0o12324", specify X='O' and base=8.       */
+/* eg: to parse bin str="-0B01010", specify X='B' and base=2.       */
+/* Failure of conversion is indicated by result where *endptr==str. */
+static long int strtol0X(const char * str,
+                         const char * *endptr,
+                         char X,
+                         int base)
+{
+    long int val;               /* stores result */
+    int s = 1;                    /* sign is +1 or -1 */
+    const char *ptr = str;        /* ptr to current position in str */
+
+    /* skip leading whitespace */
+    while (isspace(*ptr))
+        ptr++;
+    /* printf("1) %s\n",ptr); */
+
+    /* scan optional sign character */
+    switch (*ptr)
+    {
+    case '+':
+        ptr++;
+        s = 1;
+        break;
+    case '-':
+        ptr++;
+        s = -1;
+        break;
+    default:
+        s = 1;
+        break;
+    }
+    /* printf("2) %s\n",ptr); */
+
+    /* '0X' prefix */
+    if ((*ptr++) != '0')
+    {
+        /* printf("failed to detect '0'\n"); */
+        *endptr = str;
+        return 0;
+    }
+    /* printf("3) %s\n",ptr); */
+    if (toupper(*ptr++) != toupper(X))
+    {
+        /* printf("failed to detect '%c'\n",X); */
+        *endptr = str;
+        return 0;
+    }
+    /* printf("4) %s\n",ptr); */
+
+    /* attempt conversion on remainder of string using strtol() */
+    val = strtol(ptr, (char * *)endptr, base);
+    if (*endptr == ptr)
+    {
+        /* conversion failed */
+        *endptr = str;
+        return 0;
+    }
+
+    /* success */
+    return s * val;
+}
+
+
+/* Returns 1 if str matches suffix (case insensitive).    */
+/* Str may contain trailing whitespace, but nothing else. */
+static int detectsuffix(const char *str, const char *suffix)
+{
+    /* scan pairwise through strings until mismatch detected */
+    while( toupper(*str) == toupper(*suffix) )
+    {
+        /* printf("'%c' '%c'\n", *str, *suffix); */
+
+        /* return 1 (success) if match persists until the string terminator */
+        if (*str == '\0')
+            return 1;
+
+        /* next chars */
+        str++;
+        suffix++;
+    }
+    /* printf("'%c' '%c' mismatch\n", *str, *suffix); */
+
+    /* return 0 (fail) if the matching did not consume the entire suffix */
+    if (*suffix != 0)
+        return 0;   /* failed to consume entire suffix */
+
+    /* skip any remaining whitespace in str */
+    while (isspace(*str))
+        str++;
+
+    /* return 1 (success) if we have reached end of str else return 0 (fail) */
+    return (*str == '\0') ? 1 : 0;
+}
+
+
+static int arg_int_scanfn(struct arg_int *parent, const char *argval)
+{
+    int errorcode = 0;
+
+    if (parent->count == parent->hdr.maxcount)
+    {
+        /* maximum number of arguments exceeded */
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* a valid argument with no argument value was given. */
+        /* This happens when an optional argument value was invoked. */
+        /* leave parent arguiment value unaltered but still count the argument. */
+        parent->count++;
+    }
+    else
+    {
+        long int val;
+        const char *end;
+
+        /* attempt to extract hex integer (eg: +0x123) from argval into val conversion */
+        val = strtol0X(argval, &end, 'X', 16);
+        if (end == argval)
+        {
+            /* hex failed, attempt octal conversion (eg +0o123) */
+            val = strtol0X(argval, &end, 'O', 8);
+            if (end == argval)
+            {
+                /* octal failed, attempt binary conversion (eg +0B101) */
+                val = strtol0X(argval, &end, 'B', 2);
+                if (end == argval)
+                {
+                    /* binary failed, attempt decimal conversion with no prefix (eg 1234) */
+                    val = strtol(argval, (char * *)&end, 10);
+                    if (end == argval)
+                    {
+                        /* all supported number formats failed */
+                        return EBADINT;
+                    }
+                }
+            }
+        }
+
+        /* Safety check for integer overflow. WARNING: this check    */
+        /* achieves nothing on machines where size(int)==size(long). */
+        if ( val > INT_MAX || val < INT_MIN )
+            errorcode = EOVERFLOW;
+
+        /* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */
+        /* We need to be mindful of integer overflows when using such big numbers.   */
+        if (detectsuffix(end, "KB"))             /* kilobytes */
+        {
+            if ( val > (INT_MAX / 1024) || val < (INT_MIN / 1024) )
+                errorcode = EOVERFLOW;          /* Overflow would occur if we proceed */
+            else
+                val *= 1024;                    /* 1KB = 1024 */
+        }
+        else if (detectsuffix(end, "MB"))        /* megabytes */
+        {
+            if ( val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576) )
+                errorcode = EOVERFLOW;          /* Overflow would occur if we proceed */
+            else
+                val *= 1048576;                 /* 1MB = 1024*1024 */
+        }
+        else if (detectsuffix(end, "GB"))        /* gigabytes */
+        {
+            if ( val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824) )
+                errorcode = EOVERFLOW;          /* Overflow would occur if we proceed */
+            else
+                val *= 1073741824;              /* 1GB = 1024*1024*1024 */
+        }
+        else if (!detectsuffix(end, ""))
+            errorcode = EBADINT;                /* invalid suffix detected */
+
+        /* if success then store result in parent->ival[] array */
+        if (errorcode == 0)
+            parent->ival[parent->count++] = val;
+    }
+
+    /* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */
+    return errorcode;
+}
+
+
+static int arg_int_checkfn(struct arg_int *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
+    return errorcode;
+}
+
+
+static void arg_int_errorfn(
+    struct arg_int *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    case EBADINT:
+        fprintf(fp, "invalid argument \"%s\" to option ", argval);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EOVERFLOW:
+        fputs("integer overflow at option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, " ");
+        fprintf(fp, "(%s is too large)\n", argval);
+        break;
+    }
+}
+
+
+struct arg_int * arg_int0(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_intn(shortopts, longopts, datatype, 0, 1, glossary);
+}
+
+
+struct arg_int * arg_int1(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_intn(shortopts, longopts, datatype, 1, 1, glossary);
+}
+
+
+struct arg_int * arg_intn(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    size_t nbytes;
+    struct arg_int *result;
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    nbytes = sizeof(struct arg_int)    /* storage for struct arg_int */
+             + maxcount * sizeof(int); /* storage for ival[maxcount] array */
+
+    result = (struct arg_int *)malloc(nbytes);
+    if (result)
+    {
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_HASVALUE;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.datatype  = datatype ? datatype : "<int>";
+        result->hdr.glossary  = glossary;
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_int_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_int_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_int_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_int_errorfn;
+
+        /* store the ival[maxcount] array immediately after the arg_int struct */
+        result->ival  = (int *)(result + 1);
+        result->count = 0;
+    }
+    
+    ARG_TRACE(("arg_intn() returns %p\n", result));
+    return result;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+
+static void arg_lit_resetfn(struct arg_lit *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+static int arg_lit_scanfn(struct arg_lit *parent, const char *argval)
+{
+    int errorcode = 0;
+    if (parent->count < parent->hdr.maxcount )
+        parent->count++;
+    else
+        errorcode = EMAXCOUNT;
+
+    ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval,
+               errorcode));
+    return errorcode;
+}
+
+
+static int arg_lit_checkfn(struct arg_lit *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static void arg_lit_errorfn(
+    struct arg_lit *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fprintf(fp, "%s: missing option ", progname);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        fprintf(fp, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fprintf(fp, "%s: extraneous option ", progname);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+    }
+
+    ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, fp,
+               errorcode, argval, progname));
+}
+
+
+struct arg_lit * arg_lit0(
+    const char * shortopts,
+    const char * longopts,
+    const char * glossary)
+{
+    return arg_litn(shortopts, longopts, 0, 1, glossary);
+}
+
+
+struct arg_lit * arg_lit1(
+    const char *shortopts,
+    const char *longopts,
+    const char *glossary)
+{
+    return arg_litn(shortopts, longopts, 1, 1, glossary);
+}
+
+
+struct arg_lit * arg_litn(
+    const char *shortopts,
+    const char *longopts,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    struct arg_lit *result;
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    result = (struct arg_lit *)malloc(sizeof(struct arg_lit));
+    if (result)
+    {
+        /* init the arg_hdr struct */
+        result->hdr.flag      = 0;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.datatype  = NULL;
+        result->hdr.glossary  = glossary;
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_lit_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_lit_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_lit_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_lit_errorfn;
+
+        /* init local variables */
+        result->count = 0;
+    }
+    
+    ARG_TRACE(("arg_litn() returns %p\n", result));
+    return result;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+struct arg_rem *arg_rem(const char *datatype, const char *glossary)
+{
+    struct arg_rem *result = (struct arg_rem *)malloc(sizeof(struct arg_rem));
+    if (result)
+    {
+        result->hdr.flag = 0;
+        result->hdr.shortopts = NULL;
+        result->hdr.longopts = NULL;
+        result->hdr.datatype = datatype;
+        result->hdr.glossary = glossary;
+        result->hdr.mincount = 1;
+        result->hdr.maxcount = 1;
+        result->hdr.parent = result;
+        result->hdr.resetfn = NULL;
+        result->hdr.scanfn = NULL;
+        result->hdr.checkfn = NULL;
+        result->hdr.errorfn = NULL;
+    }
+
+    ARG_TRACE(("arg_rem() returns %p\n", result));
+    return result;
+}
+
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "argtable3.h"
+
+
+#ifndef _TREX_H_
+#define _TREX_H_
+/***************************************************************
+       T-Rex a tiny regular expression library
+
+       Copyright (C) 2003-2006 Alberto Demichelis
+
+       This software is provided 'as-is', without any express
+       or implied warranty. In no event will the authors be held
+       liable for any damages arising from the use of this software.
+
+       Permission is granted to anyone to use this software for
+       any purpose, including commercial applications, and to alter
+       it and redistribute it freely, subject to the following restrictions:
+
+               1. The origin of this software must not be misrepresented;
+               you must not claim that you wrote the original software.
+               If you use this software in a product, an acknowledgment
+               in the product documentation would be appreciated but
+               is not required.
+
+               2. Altered source versions must be plainly marked as such,
+               and must not be misrepresented as being the original software.
+
+               3. This notice may not be removed or altered from any
+               source distribution.
+
+****************************************************************/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef _UNICODE
+#define TRexChar unsigned short
+#define MAX_CHAR 0xFFFF
+#define _TREXC(c) L##c
+#define trex_strlen wcslen
+#define trex_printf wprintf
+#else
+#define TRexChar char
+#define MAX_CHAR 0xFF
+#define _TREXC(c) (c)
+#define trex_strlen strlen
+#define trex_printf printf
+#endif
+
+#ifndef TREX_API
+#define TREX_API extern
+#endif
+
+#define TRex_True 1
+#define TRex_False 0
+
+#define TREX_ICASE ARG_REX_ICASE
+
+typedef unsigned int TRexBool;
+typedef struct TRex TRex;
+
+typedef struct {
+       const TRexChar *begin;
+       int len;
+} TRexMatch;
+
+TREX_API TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags);
+TREX_API void trex_free(TRex *exp);
+TREX_API TRexBool trex_match(TRex* exp, const TRexChar* text);
+TREX_API TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API TRexBool trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API int trex_getsubexpcount(TRex* exp);
+TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
+
+struct privhdr
+{
+    const char *pattern;
+    int flags;
+};
+
+
+static void arg_rex_resetfn(struct arg_rex *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+static int arg_rex_scanfn(struct arg_rex *parent, const char *argval)
+{
+    int errorcode = 0;
+    const TRexChar *error = NULL;
+    TRex *rex = NULL;
+    TRexBool is_match = TRex_False;
+
+    if (parent->count == parent->hdr.maxcount )
+    {
+        /* maximum number of arguments exceeded */
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* a valid argument with no argument value was given. */
+        /* This happens when an optional argument value was invoked. */
+        /* leave parent argument value unaltered but still count the argument. */
+        parent->count++;
+    }
+    else
+    {
+        struct privhdr *priv = (struct privhdr *)parent->hdr.priv;
+
+        /* test the current argument value for a match with the regular expression */
+        /* if a match is detected, record the argument value in the arg_rex struct */
+
+        rex = trex_compile(priv->pattern, &error, priv->flags);
+        is_match = trex_match(rex, argval);
+        if (!is_match)
+            errorcode = EREGNOMATCH;
+        else
+            parent->sval[parent->count++] = argval;
+
+        trex_free(rex);
+    }
+
+    ARG_TRACE(("%s:scanfn(%p) returns %d\n",__FILE__,parent,errorcode));
+    return errorcode;
+}
+
+static int arg_rex_checkfn(struct arg_rex *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    //struct privhdr *priv = (struct privhdr*)parent->hdr.priv;
+
+    /* free the regex "program" we constructed in resetfn */
+    //regfree(&(priv->regex));
+
+    /*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
+    return errorcode;
+}
+
+static void arg_rex_errorfn(struct arg_rex *parent,
+                    FILE *fp,
+                    int errorcode,
+                    const char *argval,
+                    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    case EREGNOMATCH:
+        fputs("illegal value  ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+
+    default:
+    {
+        //char errbuff[256];
+        //regerror(errorcode, NULL, errbuff, sizeof(errbuff));
+        //printf("%s\n", errbuff);
+    }
+    break;
+    }
+}
+
+
+struct arg_rex * arg_rex0(const char * shortopts,
+                          const char * longopts,
+                          const char * pattern,
+                          const char *datatype,
+                          int flags,
+                          const char *glossary)
+{
+    return arg_rexn(shortopts,
+                    longopts,
+                    pattern,
+                    datatype,
+                    0,
+                    1,
+                    flags,
+                    glossary);
+}
+
+struct arg_rex * arg_rex1(const char * shortopts,
+                          const char * longopts,
+                          const char * pattern,
+                          const char *datatype,
+                          int flags,
+                          const char *glossary)
+{
+    return arg_rexn(shortopts,
+                    longopts,
+                    pattern,
+                    datatype,
+                    1,
+                    1,
+                    flags,
+                    glossary);
+}
+
+
+struct arg_rex * arg_rexn(const char * shortopts,
+                          const char * longopts,
+                          const char * pattern,
+                          const char *datatype,
+                          int mincount,
+                          int maxcount,
+                          int flags,
+                          const char *glossary)
+{
+    size_t nbytes;
+    struct arg_rex *result;
+    struct privhdr *priv;
+    int i;
+    const TRexChar *error = NULL;
+    TRex *rex = NULL;
+
+    if (!pattern)
+    {
+        printf(
+            "argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n");
+        printf("argtable: Bad argument table.\n");
+        return NULL;
+    }
+
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    nbytes = sizeof(struct arg_rex)       /* storage for struct arg_rex */
+             + sizeof(struct privhdr)     /* storage for private arg_rex data */
+             + maxcount * sizeof(char *);  /* storage for sval[maxcount] array */
+
+    result = (struct arg_rex *)malloc(nbytes);
+    if (result == NULL)
+        return result;
+
+    /* init the arg_hdr struct */
+    result->hdr.flag      = ARG_HASVALUE;
+    result->hdr.shortopts = shortopts;
+    result->hdr.longopts  = longopts;
+    result->hdr.datatype  = datatype ? datatype : pattern;
+    result->hdr.glossary  = glossary;
+    result->hdr.mincount  = mincount;
+    result->hdr.maxcount  = maxcount;
+    result->hdr.parent    = result;
+    result->hdr.resetfn   = (arg_resetfn *)arg_rex_resetfn;
+    result->hdr.scanfn    = (arg_scanfn *)arg_rex_scanfn;
+    result->hdr.checkfn   = (arg_checkfn *)arg_rex_checkfn;
+    result->hdr.errorfn   = (arg_errorfn *)arg_rex_errorfn;
+
+    /* store the arg_rex_priv struct immediately after the arg_rex struct */
+    result->hdr.priv  = result + 1;
+    priv = (struct privhdr *)(result->hdr.priv);
+    priv->pattern = pattern;
+    priv->flags = flags;
+
+    /* store the sval[maxcount] array immediately after the arg_rex_priv struct */
+    result->sval  = (const char * *)(priv + 1);
+    result->count = 0;
+
+    /* foolproof the string pointers by initializing them to reference empty strings */
+    for (i = 0; i < maxcount; i++)
+        result->sval[i] = "";
+
+    /* here we construct and destroy a regex representation of the regular
+     * expression for no other reason than to force any regex errors to be
+     * trapped now rather than later. If we don't, then errors may go undetected
+     * until an argument is actually parsed.
+     */
+
+    rex = trex_compile(priv->pattern, &error, priv->flags);
+    if (rex == NULL)
+    {
+        ARG_LOG(("argtable: %s \"%s\"\n", error ? error : _TREXC("undefined"), priv->pattern));
+        ARG_LOG(("argtable: Bad argument table.\n"));
+    }
+
+    trex_free(rex);
+
+    ARG_TRACE(("arg_rexn() returns %p\n", result));
+    return result;
+}
+
+
+
+/* see copyright notice in trex.h */
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <setjmp.h>
+
+#ifdef _UINCODE
+#define scisprint iswprint
+#define scstrlen wcslen
+#define scprintf wprintf
+#define _SC(x) L(x)
+#else
+#define scisprint isprint
+#define scstrlen strlen
+#define scprintf printf
+#define _SC(x) (x)
+#endif
+
+#ifdef _DEBUG
+#include <stdio.h>
+
+static const TRexChar *g_nnames[] =
+{
+       _SC("NONE"),_SC("OP_GREEDY"),   _SC("OP_OR"),
+       _SC("OP_EXPR"),_SC("OP_NOCAPEXPR"),_SC("OP_DOT"),       _SC("OP_CLASS"),
+       _SC("OP_CCLASS"),_SC("OP_NCLASS"),_SC("OP_RANGE"),_SC("OP_CHAR"),
+       _SC("OP_EOL"),_SC("OP_BOL"),_SC("OP_WB")
+};
+
+#endif
+#define OP_GREEDY              (MAX_CHAR+1) // * + ? {n}
+#define OP_OR                  (MAX_CHAR+2)
+#define OP_EXPR                        (MAX_CHAR+3) //parentesis ()
+#define OP_NOCAPEXPR   (MAX_CHAR+4) //parentesis (?:)
+#define OP_DOT                 (MAX_CHAR+5)
+#define OP_CLASS               (MAX_CHAR+6)
+#define OP_CCLASS              (MAX_CHAR+7)
+#define OP_NCLASS              (MAX_CHAR+8) //negates class the [^
+#define OP_RANGE               (MAX_CHAR+9)
+#define OP_CHAR                        (MAX_CHAR+10)
+#define OP_EOL                 (MAX_CHAR+11)
+#define OP_BOL                 (MAX_CHAR+12)
+#define OP_WB                  (MAX_CHAR+13)
+
+#define TREX_SYMBOL_ANY_CHAR ('.')
+#define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+')
+#define TREX_SYMBOL_GREEDY_ZERO_OR_MORE ('*')
+#define TREX_SYMBOL_GREEDY_ZERO_OR_ONE ('?')
+#define TREX_SYMBOL_BRANCH ('|')
+#define TREX_SYMBOL_END_OF_STRING ('$')
+#define TREX_SYMBOL_BEGINNING_OF_STRING ('^')
+#define TREX_SYMBOL_ESCAPE_CHAR ('\\')
+
+
+typedef int TRexNodeType;
+
+typedef struct tagTRexNode{
+       TRexNodeType type;
+       int left;
+       int right;
+       int next;
+}TRexNode;
+
+struct TRex{
+       const TRexChar *_eol;
+       const TRexChar *_bol;
+       const TRexChar *_p;
+       int _first;
+       int _op;
+       TRexNode *_nodes;
+       int _nallocated;
+       int _nsize;
+       int _nsubexpr;
+       TRexMatch *_matches;
+       int _currsubexp;
+       void *_jmpbuf;
+       const TRexChar **_error;
+       int _flags;
+};
+
+static int trex_list(TRex *exp);
+
+static int trex_newnode(TRex *exp, TRexNodeType type)
+{
+       TRexNode n;
+       int newid;
+       n.type = type;
+       n.next = n.right = n.left = -1;
+       if(type == OP_EXPR)
+               n.right = exp->_nsubexpr++;
+       if(exp->_nallocated < (exp->_nsize + 1)) {
+               exp->_nallocated *= 2;
+               exp->_nodes = (TRexNode *)realloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
+       }
+       exp->_nodes[exp->_nsize++] = n;
+       newid = exp->_nsize - 1;
+       return (int)newid;
+}
+
+static void trex_error(TRex *exp,const TRexChar *error)
+{
+       if(exp->_error) *exp->_error = error;
+       longjmp(*((jmp_buf*)exp->_jmpbuf),-1);
+}
+
+static void trex_expect(TRex *exp, int n){
+       if((*exp->_p) != n)
+               trex_error(exp, _SC("expected paren"));
+       exp->_p++;
+}
+
+static TRexChar trex_escapechar(TRex *exp)
+{
+       if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR){
+               exp->_p++;
+               switch(*exp->_p) {
+               case 'v': exp->_p++; return '\v';
+               case 'n': exp->_p++; return '\n';
+               case 't': exp->_p++; return '\t';
+               case 'r': exp->_p++; return '\r';
+               case 'f': exp->_p++; return '\f';
+               default: return (*exp->_p++);
+               }
+       } else if(!scisprint(*exp->_p)) trex_error(exp,_SC("letter expected"));
+       return (*exp->_p++);
+}
+
+static int trex_charclass(TRex *exp,int classid)
+{
+       int n = trex_newnode(exp,OP_CCLASS);
+       exp->_nodes[n].left = classid;
+       return n;
+}
+
+static int trex_charnode(TRex *exp,TRexBool isclass)
+{
+       TRexChar t;
+       if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
+               exp->_p++;
+               switch(*exp->_p) {
+                       case 'n': exp->_p++; return trex_newnode(exp,'\n');
+                       case 't': exp->_p++; return trex_newnode(exp,'\t');
+                       case 'r': exp->_p++; return trex_newnode(exp,'\r');
+                       case 'f': exp->_p++; return trex_newnode(exp,'\f');
+                       case 'v': exp->_p++; return trex_newnode(exp,'\v');
+                       case 'a': case 'A': case 'w': case 'W': case 's': case 'S':
+                       case 'd': case 'D': case 'x': case 'X': case 'c': case 'C':
+                       case 'p': case 'P': case 'l': case 'u':
+                               {
+                               t = *exp->_p; exp->_p++;
+                               return trex_charclass(exp,t);
+                               }
+                       case 'b':
+                       case 'B':
+                               if(!isclass) {
+                                       int node = trex_newnode(exp,OP_WB);
+                                       exp->_nodes[node].left = *exp->_p;
+                                       exp->_p++;
+                                       return node;
+                               } //else default
+                       default:
+                               t = *exp->_p; exp->_p++;
+                               return trex_newnode(exp,t);
+               }
+       }
+       else if(!scisprint(*exp->_p)) {
+
+               trex_error(exp,_SC("letter expected"));
+       }
+       t = *exp->_p; exp->_p++;
+       return trex_newnode(exp,t);
+}
+static int trex_class(TRex *exp)
+{
+       int ret = -1;
+       int first = -1,chain;
+       if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING){
+               ret = trex_newnode(exp,OP_NCLASS);
+               exp->_p++;
+       }else ret = trex_newnode(exp,OP_CLASS);
+
+       if(*exp->_p == ']') trex_error(exp,_SC("empty class"));
+       chain = ret;
+       while(*exp->_p != ']' && exp->_p != exp->_eol) {
+               if(*exp->_p == '-' && first != -1){
+                       int r,t;
+                       if(*exp->_p++ == ']') trex_error(exp,_SC("unfinished range"));
+                       r = trex_newnode(exp,OP_RANGE);
+                       if(first>*exp->_p) trex_error(exp,_SC("invalid range"));
+                       if(exp->_nodes[first].type == OP_CCLASS) trex_error(exp,_SC("cannot use character classes in ranges"));
+                       exp->_nodes[r].left = exp->_nodes[first].type;
+                       t = trex_escapechar(exp);
+                       exp->_nodes[r].right = t;
+            exp->_nodes[chain].next = r;
+                       chain = r;
+                       first = -1;
+               }
+               else{
+                       if(first!=-1){
+                               int c = first;
+                               exp->_nodes[chain].next = c;
+                               chain = c;
+                               first = trex_charnode(exp,TRex_True);
+                       }
+                       else{
+                               first = trex_charnode(exp,TRex_True);
+                       }
+               }
+       }
+       if(first!=-1){
+               int c = first;
+               exp->_nodes[chain].next = c;
+               chain = c;
+               first = -1;
+       }
+       /* hack? */
+       exp->_nodes[ret].left = exp->_nodes[ret].next;
+       exp->_nodes[ret].next = -1;
+       return ret;
+}
+
+static int trex_parsenumber(TRex *exp)
+{
+       int ret = *exp->_p-'0';
+       int positions = 10;
+       exp->_p++;
+       while(isdigit(*exp->_p)) {
+               ret = ret*10+(*exp->_p++-'0');
+               if(positions==1000000000) trex_error(exp,_SC("overflow in numeric constant"));
+               positions *= 10;
+       };
+       return ret;
+}
+
+static int trex_element(TRex *exp)
+{
+       int ret = -1;
+       switch(*exp->_p)
+       {
+       case '(': {
+               int expr,newn;
+               exp->_p++;
+
+
+               if(*exp->_p =='?') {
+                       exp->_p++;
+                       trex_expect(exp,':');
+                       expr = trex_newnode(exp,OP_NOCAPEXPR);
+               }
+               else
+                       expr = trex_newnode(exp,OP_EXPR);
+               newn = trex_list(exp);
+               exp->_nodes[expr].left = newn;
+               ret = expr;
+               trex_expect(exp,')');
+                         }
+                         break;
+       case '[':
+               exp->_p++;
+               ret = trex_class(exp);
+               trex_expect(exp,']');
+               break;
+       case TREX_SYMBOL_END_OF_STRING: exp->_p++; ret = trex_newnode(exp,OP_EOL);break;
+       case TREX_SYMBOL_ANY_CHAR: exp->_p++; ret = trex_newnode(exp,OP_DOT);break;
+       default:
+               ret = trex_charnode(exp,TRex_False);
+               break;
+       }
+
+       {
+               TRexBool isgreedy = TRex_False;
+               unsigned short p0 = 0, p1 = 0;
+               switch(*exp->_p){
+                       case TREX_SYMBOL_GREEDY_ZERO_OR_MORE: p0 = 0; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
+                       case TREX_SYMBOL_GREEDY_ONE_OR_MORE: p0 = 1; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
+                       case TREX_SYMBOL_GREEDY_ZERO_OR_ONE: p0 = 0; p1 = 1; exp->_p++; isgreedy = TRex_True; break;
+                       case '{':
+                               exp->_p++;
+                               if(!isdigit(*exp->_p)) trex_error(exp,_SC("number expected"));
+                               p0 = (unsigned short)trex_parsenumber(exp);
+                               /*******************************/
+                               switch(*exp->_p) {
+                       case '}':
+                               p1 = p0; exp->_p++;
+                               break;
+                       case ',':
+                               exp->_p++;
+                               p1 = 0xFFFF;
+                               if(isdigit(*exp->_p)){
+                                       p1 = (unsigned short)trex_parsenumber(exp);
+                               }
+                               trex_expect(exp,'}');
+                               break;
+                       default:
+                               trex_error(exp,_SC(", or } expected"));
+               }
+               /*******************************/
+               isgreedy = TRex_True;
+               break;
+
+               }
+               if(isgreedy) {
+                       int nnode = trex_newnode(exp,OP_GREEDY);
+                       exp->_nodes[nnode].left = ret;
+                       exp->_nodes[nnode].right = ((p0)<<16)|p1;
+                       ret = nnode;
+               }
+       }
+       if((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
+               int nnode = trex_element(exp);
+               exp->_nodes[ret].next = nnode;
+       }
+
+       return ret;
+}
+
+static int trex_list(TRex *exp)
+{
+       int ret=-1,e;
+       if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
+               exp->_p++;
+               ret = trex_newnode(exp,OP_BOL);
+       }
+       e = trex_element(exp);
+       if(ret != -1) {
+               exp->_nodes[ret].next = e;
+       }
+       else ret = e;
+
+       if(*exp->_p == TREX_SYMBOL_BRANCH) {
+               int temp,tright;
+               exp->_p++;
+               temp = trex_newnode(exp,OP_OR);
+               exp->_nodes[temp].left = ret;
+               tright = trex_list(exp);
+               exp->_nodes[temp].right = tright;
+               ret = temp;
+       }
+       return ret;
+}
+
+static TRexBool trex_matchcclass(int cclass,TRexChar c)
+{
+       switch(cclass) {
+       case 'a': return isalpha(c)?TRex_True:TRex_False;
+       case 'A': return !isalpha(c)?TRex_True:TRex_False;
+       case 'w': return (isalnum(c) || c == '_')?TRex_True:TRex_False;
+       case 'W': return (!isalnum(c) && c != '_')?TRex_True:TRex_False;
+       case 's': return isspace(c)?TRex_True:TRex_False;
+       case 'S': return !isspace(c)?TRex_True:TRex_False;
+       case 'd': return isdigit(c)?TRex_True:TRex_False;
+       case 'D': return !isdigit(c)?TRex_True:TRex_False;
+       case 'x': return isxdigit(c)?TRex_True:TRex_False;
+       case 'X': return !isxdigit(c)?TRex_True:TRex_False;
+       case 'c': return iscntrl(c)?TRex_True:TRex_False;
+       case 'C': return !iscntrl(c)?TRex_True:TRex_False;
+       case 'p': return ispunct(c)?TRex_True:TRex_False;
+       case 'P': return !ispunct(c)?TRex_True:TRex_False;
+       case 'l': return islower(c)?TRex_True:TRex_False;
+       case 'u': return isupper(c)?TRex_True:TRex_False;
+       }
+       return TRex_False; /*cannot happen*/
+}
+
+static TRexBool trex_matchclass(TRex* exp,TRexNode *node,TRexChar c)
+{
+       do {
+               switch(node->type) {
+                       case OP_RANGE:
+                               if (exp->_flags & TREX_ICASE)
+                               {
+                                       if(c >= toupper(node->left) && c <= toupper(node->right)) return TRex_True;
+                                       if(c >= tolower(node->left) && c <= tolower(node->right)) return TRex_True;
+                               }
+                               else
+                               {
+                                       if(c >= node->left && c <= node->right) return TRex_True;
+                               }
+                               break;
+                       case OP_CCLASS:
+                               if(trex_matchcclass(node->left,c)) return TRex_True;
+                               break;
+                       default:
+                               if (exp->_flags & TREX_ICASE)
+                               {
+                                       if (c == tolower(node->type) || c == toupper(node->type)) return TRex_True;
+                               }
+                               else
+                               {
+                                       if(c == node->type)return TRex_True;
+                               }
+
+               }
+       } while((node->next != -1) && (node = &exp->_nodes[node->next]));
+       return TRex_False;
+}
+
+static const TRexChar *trex_matchnode(TRex* exp,TRexNode *node,const TRexChar *str,TRexNode *next)
+{
+
+       TRexNodeType type = node->type;
+       switch(type) {
+       case OP_GREEDY: {
+               //TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL;
+               TRexNode *greedystop = NULL;
+               int p0 = (node->right >> 16)&0x0000FFFF, p1 = node->right&0x0000FFFF, nmaches = 0;
+               const TRexChar *s=str, *good = str;
+
+               if(node->next != -1) {
+                       greedystop = &exp->_nodes[node->next];
+               }
+               else {
+                       greedystop = next;
+               }
+
+               while((nmaches == 0xFFFF || nmaches < p1)) {
+
+                       const TRexChar *stop;
+                       if(!(s = trex_matchnode(exp,&exp->_nodes[node->left],s,greedystop)))
+                               break;
+                       nmaches++;
+                       good=s;
+                       if(greedystop) {
+                               //checks that 0 matches satisfy the expression(if so skips)
+                               //if not would always stop(for instance if is a '?')
+                               if(greedystop->type != OP_GREEDY ||
+                               (greedystop->type == OP_GREEDY && ((greedystop->right >> 16)&0x0000FFFF) != 0))
+                               {
+                                       TRexNode *gnext = NULL;
+                                       if(greedystop->next != -1) {
+                                               gnext = &exp->_nodes[greedystop->next];
+                                       }else if(next && next->next != -1){
+                                               gnext = &exp->_nodes[next->next];
+                                       }
+                                       stop = trex_matchnode(exp,greedystop,s,gnext);
+                                       if(stop) {
+                                               //if satisfied stop it
+                                               if(p0 == p1 && p0 == nmaches) break;
+                                               else if(nmaches >= p0 && p1 == 0xFFFF) break;
+                                               else if(nmaches >= p0 && nmaches <= p1) break;
+                                       }
+                               }
+                       }
+
+                       if(s >= exp->_eol)
+                               break;
+               }
+               if(p0 == p1 && p0 == nmaches) return good;
+               else if(nmaches >= p0 && p1 == 0xFFFF) return good;
+               else if(nmaches >= p0 && nmaches <= p1) return good;
+               return NULL;
+       }
+       case OP_OR: {
+                       const TRexChar *asd = str;
+                       TRexNode *temp=&exp->_nodes[node->left];
+                       while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
+                               if(temp->next != -1)
+                                       temp = &exp->_nodes[temp->next];
+                               else
+                                       return asd;
+                       }
+                       asd = str;
+                       temp = &exp->_nodes[node->right];
+                       while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
+                               if(temp->next != -1)
+                                       temp = &exp->_nodes[temp->next];
+                               else
+                                       return asd;
+                       }
+                       return NULL;
+                       break;
+       }
+       case OP_EXPR:
+       case OP_NOCAPEXPR:{
+                       TRexNode *n = &exp->_nodes[node->left];
+                       const TRexChar *cur = str;
+                       int capture = -1;
+                       if(node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) {
+                               capture = exp->_currsubexp;
+                               exp->_matches[capture].begin = cur;
+                               exp->_currsubexp++;
+                       }
+
+                       do {
+                               TRexNode *subnext = NULL;
+                               if(n->next != -1) {
+                                       subnext = &exp->_nodes[n->next];
+                               }else {
+                                       subnext = next;
+                               }
+                               if(!(cur = trex_matchnode(exp,n,cur,subnext))) {
+                                       if(capture != -1){
+                                               exp->_matches[capture].begin = 0;
+                                               exp->_matches[capture].len = 0;
+                                       }
+                                       return NULL;
+                               }
+                       } while((n->next != -1) && (n = &exp->_nodes[n->next]));
+
+                       if(capture != -1)
+                               exp->_matches[capture].len = cur - exp->_matches[capture].begin;
+                       return cur;
+       }
+       case OP_WB:
+               if((str == exp->_bol && !isspace(*str))
+                || ((str == exp->_eol && !isspace(*(str-1))))
+                || ((!isspace(*str) && isspace(*(str+1))))
+                || ((isspace(*str) && !isspace(*(str+1)))) ) {
+                       return (node->left == 'b')?str:NULL;
+               }
+               return (node->left == 'b')?NULL:str;
+       case OP_BOL:
+               if(str == exp->_bol) return str;
+               return NULL;
+       case OP_EOL:
+               if(str == exp->_eol) return str;
+               return NULL;
+       case OP_DOT:
+               str++;
+               return str;
+       case OP_NCLASS:
+       case OP_CLASS:
+               if(trex_matchclass(exp,&exp->_nodes[node->left],*str)?(type == OP_CLASS?TRex_True:TRex_False):(type == OP_NCLASS?TRex_True:TRex_False)) {
+                        str++;
+                       return str;
+               }
+               return NULL;
+       case OP_CCLASS:
+               if(trex_matchcclass(node->left,*str)) {
+                        str++;
+                       return str;
+               }
+               return NULL;
+       default: /* char */
+               if (exp->_flags & TREX_ICASE)
+               {
+                       if(*str != tolower(node->type) && *str != toupper(node->type)) return NULL;
+               }
+               else
+               {
+                       if (*str != node->type) return NULL;
+               }
+               str++;
+               return str;
+       }
+       return NULL;
+}
+
+/* public api */
+TRex *trex_compile(const TRexChar *pattern,const TRexChar **error,int flags)
+{
+       TRex *exp = (TRex *)malloc(sizeof(TRex));
+       exp->_eol = exp->_bol = NULL;
+       exp->_p = pattern;
+       exp->_nallocated = (int)scstrlen(pattern) * sizeof(TRexChar);
+       exp->_nodes = (TRexNode *)malloc(exp->_nallocated * sizeof(TRexNode));
+       exp->_nsize = 0;
+       exp->_matches = 0;
+       exp->_nsubexpr = 0;
+       exp->_first = trex_newnode(exp,OP_EXPR);
+       exp->_error = error;
+       exp->_jmpbuf = malloc(sizeof(jmp_buf));
+       exp->_flags = flags;
+       if(setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) {
+               int res = trex_list(exp);
+               exp->_nodes[exp->_first].left = res;
+               if(*exp->_p!='\0')
+                       trex_error(exp,_SC("unexpected character"));
+#ifdef _DEBUG
+               {
+                       int nsize,i;
+                       TRexNode *t;
+                       nsize = exp->_nsize;
+                       t = &exp->_nodes[0];
+                       scprintf(_SC("\n"));
+                       for(i = 0;i < nsize; i++) {
+                               if(exp->_nodes[i].type>MAX_CHAR)
+                                       scprintf(_SC("[%02d] %10s "),i,g_nnames[exp->_nodes[i].type-MAX_CHAR]);
+                               else
+                                       scprintf(_SC("[%02d] %10c "),i,exp->_nodes[i].type);
+                               scprintf(_SC("left %02d right %02d next %02d\n"),exp->_nodes[i].left,exp->_nodes[i].right,exp->_nodes[i].next);
+                       }
+                       scprintf(_SC("\n"));
+               }
+#endif
+               exp->_matches = (TRexMatch *) malloc(exp->_nsubexpr * sizeof(TRexMatch));
+               memset(exp->_matches,0,exp->_nsubexpr * sizeof(TRexMatch));
+       }
+       else{
+               trex_free(exp);
+               return NULL;
+       }
+       return exp;
+}
+
+void trex_free(TRex *exp)
+{
+       if(exp) {
+               if(exp->_nodes) free(exp->_nodes);
+               if(exp->_jmpbuf) free(exp->_jmpbuf);
+               if(exp->_matches) free(exp->_matches);
+               free(exp);
+       }
+}
+
+TRexBool trex_match(TRex* exp,const TRexChar* text)
+{
+       const TRexChar* res = NULL;
+       exp->_bol = text;
+       exp->_eol = text + scstrlen(text);
+       exp->_currsubexp = 0;
+       res = trex_matchnode(exp,exp->_nodes,text,NULL);
+       if(res == NULL || res != exp->_eol)
+               return TRex_False;
+       return TRex_True;
+}
+
+TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
+{
+       const TRexChar *cur = NULL;
+       int node = exp->_first;
+       if(text_begin >= text_end) return TRex_False;
+       exp->_bol = text_begin;
+       exp->_eol = text_end;
+       do {
+               cur = text_begin;
+               while(node != -1) {
+                       exp->_currsubexp = 0;
+                       cur = trex_matchnode(exp,&exp->_nodes[node],cur,NULL);
+                       if(!cur)
+                               break;
+                       node = exp->_nodes[node].next;
+               }
+               text_begin++;
+       } while(cur == NULL && text_begin != text_end);
+
+       if(cur == NULL)
+               return TRex_False;
+
+       --text_begin;
+
+       if(out_begin) *out_begin = text_begin;
+       if(out_end) *out_end = cur;
+       return TRex_True;
+}
+
+TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
+{
+       return trex_searchrange(exp,text,text + scstrlen(text),out_begin,out_end);
+}
+
+int trex_getsubexpcount(TRex* exp)
+{
+       return exp->_nsubexpr;
+}
+
+TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp)
+{
+       if( n<0 || n >= exp->_nsubexpr) return TRex_False;
+       *subexp = exp->_matches[n];
+       return TRex_True;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+
+#include "argtable3.h"
+
+
+static void arg_str_resetfn(struct arg_str *parent)
+{
+    ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+    parent->count = 0;
+}
+
+
+static int arg_str_scanfn(struct arg_str *parent, const char *argval)
+{
+    int errorcode = 0;
+
+    if (parent->count == parent->hdr.maxcount)
+    {
+        /* maximum number of arguments exceeded */
+        errorcode = EMAXCOUNT;
+    }
+    else if (!argval)
+    {
+        /* a valid argument with no argument value was given. */
+        /* This happens when an optional argument value was invoked. */
+        /* leave parent arguiment value unaltered but still count the argument. */
+        parent->count++;
+    }
+    else
+    {
+        parent->sval[parent->count++] = argval;
+    }
+
+    ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static int arg_str_checkfn(struct arg_str *parent)
+{
+    int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+    
+    ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
+    return errorcode;
+}
+
+
+static void arg_str_errorfn(
+    struct arg_str *parent,
+    FILE *fp,
+    int errorcode,
+    const char *argval,
+    const char *progname)
+{
+    const char *shortopts = parent->hdr.shortopts;
+    const char *longopts  = parent->hdr.longopts;
+    const char *datatype  = parent->hdr.datatype;
+
+    /* make argval NULL safe */
+    argval = argval ? argval : "";
+
+    fprintf(fp, "%s: ", progname);
+    switch(errorcode)
+    {
+    case EMINCOUNT:
+        fputs("missing option ", fp);
+        arg_print_option(fp, shortopts, longopts, datatype, "\n");
+        break;
+
+    case EMAXCOUNT:
+        fputs("excess option ", fp);
+        arg_print_option(fp, shortopts, longopts, argval, "\n");
+        break;
+    }
+}
+
+
+struct arg_str * arg_str0(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_strn(shortopts, longopts, datatype, 0, 1, glossary);
+}
+
+
+struct arg_str * arg_str1(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    const char *glossary)
+{
+    return arg_strn(shortopts, longopts, datatype, 1, 1, glossary);
+}
+
+
+struct arg_str * arg_strn(
+    const char *shortopts,
+    const char *longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary)
+{
+    size_t nbytes;
+    struct arg_str *result;
+
+    /* should not allow this stupid error */
+    /* we should return an error code warning this logic error */
+    /* foolproof things by ensuring maxcount is not less than mincount */
+    maxcount = (maxcount < mincount) ? mincount : maxcount;
+
+    nbytes = sizeof(struct arg_str)     /* storage for struct arg_str */
+             + maxcount * sizeof(char *); /* storage for sval[maxcount] array */
+
+    result = (struct arg_str *)malloc(nbytes);
+    if (result)
+    {
+        int i;
+
+        /* init the arg_hdr struct */
+        result->hdr.flag      = ARG_HASVALUE;
+        result->hdr.shortopts = shortopts;
+        result->hdr.longopts  = longopts;
+        result->hdr.datatype  = datatype ? datatype : "<string>";
+        result->hdr.glossary  = glossary;
+        result->hdr.mincount  = mincount;
+        result->hdr.maxcount  = maxcount;
+        result->hdr.parent    = result;
+        result->hdr.resetfn   = (arg_resetfn *)arg_str_resetfn;
+        result->hdr.scanfn    = (arg_scanfn *)arg_str_scanfn;
+        result->hdr.checkfn   = (arg_checkfn *)arg_str_checkfn;
+        result->hdr.errorfn   = (arg_errorfn *)arg_str_errorfn;
+
+        /* store the sval[maxcount] array immediately after the arg_str struct */
+        result->sval  = (const char * *)(result + 1);
+        result->count = 0;
+
+        /* foolproof the string pointers by initialising them to reference empty strings */
+        for (i = 0; i < maxcount; i++)
+            result->sval[i] = "";
+    }
+    
+    ARG_TRACE(("arg_strn() returns %p\n", result));
+    return result;
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+#include "argtable3.h"
+
+static
+void arg_register_error(struct arg_end *end,
+                        void *parent,
+                        int error,
+                        const char *argval)
+{
+    /* printf("arg_register_error(%p,%p,%d,%s)\n",end,parent,error,argval); */
+    if (end->count < end->hdr.maxcount)
+    {
+        end->error[end->count] = error;
+        end->parent[end->count] = parent;
+        end->argval[end->count] = argval;
+        end->count++;
+    }
+    else
+    {
+        end->error[end->hdr.maxcount - 1]  = ARG_ELIMIT;
+        end->parent[end->hdr.maxcount - 1] = end;
+        end->argval[end->hdr.maxcount - 1] = NULL;
+    }
+}
+
+
+/*
+ * Return index of first table entry with a matching short option
+ * or -1 if no match was found.
+ */
+static
+int find_shortoption(struct arg_hdr * *table, char shortopt)
+{
+    int tabindex;
+    for(tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+    {
+        if (table[tabindex]->shortopts &&
+            strchr(table[tabindex]->shortopts, shortopt))
+            return tabindex;
+    }
+    return -1;
+}
+
+
+struct longoptions
+{
+    int getoptval;
+    int noptions;
+    struct option *options;
+};
+
+#if 0
+static
+void dump_longoptions(struct longoptions * longoptions)
+{
+    int i;
+    printf("getoptval = %d\n", longoptions->getoptval);
+    printf("noptions  = %d\n", longoptions->noptions);
+    for (i = 0; i < longoptions->noptions; i++)
+    {
+        printf("options[%d].name    = \"%s\"\n",
+               i,
+               longoptions->options[i].name);
+        printf("options[%d].has_arg = %d\n", i, longoptions->options[i].has_arg);
+        printf("options[%d].flag    = %p\n", i, longoptions->options[i].flag);
+        printf("options[%d].val     = %d\n", i, longoptions->options[i].val);
+    }
+}
+#endif
+
+static
+struct longoptions * alloc_longoptions(struct arg_hdr * *table)
+{
+    struct longoptions *result;
+    size_t nbytes;
+    int noptions = 1;
+    size_t longoptlen = 0;
+    int tabindex;
+
+    /*
+     * Determine the total number of option structs required
+     * by counting the number of comma separated long options
+     * in all table entries and return the count in noptions.
+     * note: noptions starts at 1 not 0 because we getoptlong
+     * requires a NULL option entry to terminate the option array.
+     * While we are at it, count the number of chars required
+     * to store private copies of all the longoption strings
+     * and return that count in logoptlen.
+     */
+    tabindex = 0;
+    do
+    {
+        const char *longopts = table[tabindex]->longopts;
+        longoptlen += (longopts ? strlen(longopts) : 0) + 1;
+        while (longopts)
+        {
+            noptions++;
+            longopts = strchr(longopts + 1, ',');
+        }
+    } while(!(table[tabindex++]->flag & ARG_TERMINATOR));
+    /*printf("%d long options consuming %d chars in total\n",noptions,longoptlen);*/
+
+
+    /* allocate storage for return data structure as: */
+    /* (struct longoptions) + (struct options)[noptions] + char[longoptlen] */
+    nbytes = sizeof(struct longoptions)
+             + sizeof(struct option) * noptions
+             + longoptlen;
+    result = (struct longoptions *)malloc(nbytes);
+    if (result)
+    {
+        int option_index = 0;
+        char *store;
+
+        result->getoptval = 0;
+        result->noptions = noptions;
+        result->options = (struct option *)(result + 1);
+        store = (char *)(result->options + noptions);
+
+        for(tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+        {
+            const char *longopts = table[tabindex]->longopts;
+
+            while(longopts && *longopts)
+            {
+                char *storestart = store;
+
+                /* copy progressive longopt strings into the store */
+                while (*longopts != 0 && *longopts != ',')
+                    *store++ = *longopts++;
+                *store++ = 0;
+                if (*longopts == ',')
+                    longopts++;
+                /*fprintf(stderr,"storestart=\"%s\"\n",storestart);*/
+
+                result->options[option_index].name    = storestart;
+                result->options[option_index].flag    = &(result->getoptval);
+                result->options[option_index].val     = tabindex;
+                if (table[tabindex]->flag & ARG_HASOPTVALUE)
+                    result->options[option_index].has_arg = 2;
+                else if (table[tabindex]->flag & ARG_HASVALUE)
+                    result->options[option_index].has_arg = 1;
+                else
+                    result->options[option_index].has_arg = 0;
+
+                option_index++;
+            }
+        }
+        /* terminate the options array with a zero-filled entry */
+        result->options[option_index].name    = 0;
+        result->options[option_index].has_arg = 0;
+        result->options[option_index].flag    = 0;
+        result->options[option_index].val     = 0;
+    }
+
+    /*dump_longoptions(result);*/
+    return result;
+}
+
+static
+char * alloc_shortoptions(struct arg_hdr * *table)
+{
+    char *result;
+    size_t len = 2;
+    int tabindex;
+
+    /* determine the total number of option chars required */
+    for(tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+    {
+        struct arg_hdr *hdr = table[tabindex];
+        len += 3 * (hdr->shortopts ? strlen(hdr->shortopts) : 0);
+    }
+
+    result = malloc(len);
+    if (result)
+    {
+        char *res = result;
+
+        /* add a leading ':' so getopt return codes distinguish    */
+        /* unrecognised option and options missing argument values */
+        *res++ = ':';
+
+        for(tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+        {
+            struct arg_hdr *hdr = table[tabindex];
+            const char *shortopts = hdr->shortopts;
+            while(shortopts && *shortopts)
+            {
+                *res++ = *shortopts++;
+                if (hdr->flag & ARG_HASVALUE)
+                    *res++ = ':';
+                if (hdr->flag & ARG_HASOPTVALUE)
+                    *res++ = ':';
+            }
+        }
+        /* null terminate the string */
+        *res = 0;
+    }
+
+    /*printf("alloc_shortoptions() returns \"%s\"\n",(result?result:"NULL"));*/
+    return result;
+}
+
+
+/* return index of the table terminator entry */
+static
+int arg_endindex(struct arg_hdr * *table)
+{
+    int tabindex = 0;
+    while (!(table[tabindex]->flag & ARG_TERMINATOR))
+        tabindex++;
+    return tabindex;
+}
+
+
+static
+void arg_parse_tagged(int argc,
+                      char * *argv,
+                      struct arg_hdr * *table,
+                      struct arg_end *endtable)
+{
+    struct longoptions *longoptions;
+    char *shortoptions;
+    int copt;
+
+    /*printf("arg_parse_tagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
+
+    /* allocate short and long option arrays for the given opttable[].   */
+    /* if the allocs fail then put an error msg in the last table entry. */
+    longoptions  = alloc_longoptions(table);
+    shortoptions = alloc_shortoptions(table);
+    if (!longoptions || !shortoptions)
+    {
+        /* one or both memory allocs failed */
+        arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
+        /* free anything that was allocated (this is null safe) */
+        free(shortoptions);
+        free(longoptions);
+        return;
+    }
+
+    /*dump_longoptions(longoptions);*/
+
+    /* reset getopts internal option-index to zero, and disable error reporting */
+    optind = 0;
+    opterr = 0;
+
+    /* fetch and process args using getopt_long */
+    while( (copt =
+                getopt_long(argc, argv, shortoptions, longoptions->options,
+                            NULL)) != -1)
+    {
+        /*
+           printf("optarg='%s'\n",optarg);
+           printf("optind=%d\n",optind);
+           printf("copt=%c\n",(char)copt);
+           printf("optopt=%c (%d)\n",optopt, (int)(optopt));
+         */
+        switch(copt)
+        {
+        case 0:
+        {
+            int tabindex = longoptions->getoptval;
+            void *parent  = table[tabindex]->parent;
+            /*printf("long option detected from argtable[%d]\n", tabindex);*/
+            if (optarg && optarg[0] == 0 &&
+                (table[tabindex]->flag & ARG_HASVALUE))
+            {
+                /* printf(": long option %s requires an argument\n",argv[optind-1]); */
+                arg_register_error(endtable, endtable, ARG_EMISSARG,
+                                   argv[optind - 1]);
+                /* continue to scan the (empty) argument value to enforce argument count checking */
+            }
+            if (table[tabindex]->scanfn)
+            {
+                int errorcode = table[tabindex]->scanfn(parent, optarg);
+                if (errorcode != 0)
+                    arg_register_error(endtable, parent, errorcode, optarg);
+            }
+        }
+        break;
+
+        case '?':
+            /*
+             * getopt_long() found an unrecognised short option.
+             * if it was a short option its value is in optopt
+             * if it was a long option then optopt=0
+             */
+            switch (optopt)
+            {
+            case 0:
+                /*printf("?0 unrecognised long option %s\n",argv[optind-1]);*/
+                arg_register_error(endtable, endtable, ARG_ELONGOPT,
+                                   argv[optind - 1]);
+                break;
+            default:
+                /*printf("?* unrecognised short option '%c'\n",optopt);*/
+                arg_register_error(endtable, endtable, optopt, NULL);
+                break;
+            }
+            break;
+
+        case ':':
+            /*
+             * getopt_long() found an option with its argument missing.
+             */
+            /*printf(": option %s requires an argument\n",argv[optind-1]); */
+            arg_register_error(endtable, endtable, ARG_EMISSARG,
+                               argv[optind - 1]);
+            break;
+
+        default:
+        {
+            /* getopt_long() found a valid short option */
+            int tabindex = find_shortoption(table, (char)copt);
+            /*printf("short option detected from argtable[%d]\n", tabindex);*/
+            if (tabindex == -1)
+            {
+                /* should never get here - but handle it just in case */
+                /*printf("unrecognised short option %d\n",copt);*/
+                arg_register_error(endtable, endtable, copt, NULL);
+            }
+            else
+            {
+                if (table[tabindex]->scanfn)
+                {
+                    void *parent  = table[tabindex]->parent;
+                    int errorcode = table[tabindex]->scanfn(parent, optarg);
+                    if (errorcode != 0)
+                        arg_register_error(endtable, parent, errorcode, optarg);
+                }
+            }
+            break;
+        }
+        }
+    }
+
+    free(shortoptions);
+    free(longoptions);
+}
+
+
+static
+void arg_parse_untagged(int argc,
+                        char * *argv,
+                        struct arg_hdr * *table,
+                        struct arg_end *endtable)
+{
+    int tabindex = 0;
+    int errorlast = 0;
+    const char *optarglast = NULL;
+    void *parentlast = NULL;
+
+    /*printf("arg_parse_untagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
+    while (!(table[tabindex]->flag & ARG_TERMINATOR))
+    {
+        void *parent;
+        int errorcode;
+
+        /* if we have exhausted our argv[optind] entries then we have finished */
+        if (optind >= argc)
+        {
+            /*printf("arg_parse_untagged(): argv[] exhausted\n");*/
+            return;
+        }
+
+        /* skip table entries with non-null long or short options (they are not untagged entries) */
+        if (table[tabindex]->longopts || table[tabindex]->shortopts)
+        {
+            /*printf("arg_parse_untagged(): skipping argtable[%d] (tagged argument)\n",tabindex);*/
+            tabindex++;
+            continue;
+        }
+
+        /* skip table entries with NULL scanfn */
+        if (!(table[tabindex]->scanfn))
+        {
+            /*printf("arg_parse_untagged(): skipping argtable[%d] (NULL scanfn)\n",tabindex);*/
+            tabindex++;
+            continue;
+        }
+
+        /* attempt to scan the current argv[optind] with the current     */
+        /* table[tabindex] entry. If it succeeds then keep it, otherwise */
+        /* try again with the next table[] entry.                        */
+        parent = table[tabindex]->parent;
+        errorcode = table[tabindex]->scanfn(parent, argv[optind]);
+        if (errorcode == 0)
+        {
+            /* success, move onto next argv[optind] but stay with same table[tabindex] */
+            /*printf("arg_parse_untagged(): argtable[%d] successfully matched\n",tabindex);*/
+            optind++;
+
+            /* clear the last tentative error */
+            errorlast = 0;
+        }
+        else
+        {
+            /* failure, try same argv[optind] with next table[tabindex] entry */
+            /*printf("arg_parse_untagged(): argtable[%d] failed match\n",tabindex);*/
+            tabindex++;
+
+            /* remember this as a tentative error we may wish to reinstate later */
+            errorlast = errorcode;
+            optarglast = argv[optind];
+            parentlast = parent;
+        }
+
+    }
+
+    /* if a tenative error still remains at this point then register it as a proper error */
+    if (errorlast)
+    {
+        arg_register_error(endtable, parentlast, errorlast, optarglast);
+        optind++;
+    }
+
+    /* only get here when not all argv[] entries were consumed */
+    /* register an error for each unused argv[] entry */
+    while (optind < argc)
+    {
+        /*printf("arg_parse_untagged(): argv[%d]=\"%s\" not consumed\n",optind,argv[optind]);*/
+        arg_register_error(endtable, endtable, ARG_ENOMATCH, argv[optind++]);
+    }
+
+    return;
+}
+
+
+static
+void arg_parse_check(struct arg_hdr * *table, struct arg_end *endtable)
+{
+    int tabindex = 0;
+    /* printf("arg_parse_check()\n"); */
+    do
+    {
+        if (table[tabindex]->checkfn)
+        {
+            void *parent  = table[tabindex]->parent;
+            int errorcode = table[tabindex]->checkfn(parent);
+            if (errorcode != 0)
+                arg_register_error(endtable, parent, errorcode, NULL);
+        }
+    } while(!(table[tabindex++]->flag & ARG_TERMINATOR));
+}
+
+
+static
+void arg_reset(void * *argtable)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int tabindex = 0;
+    /*printf("arg_reset(%p)\n",argtable);*/
+    do
+    {
+        if (table[tabindex]->resetfn)
+            table[tabindex]->resetfn(table[tabindex]->parent);
+    } while(!(table[tabindex++]->flag & ARG_TERMINATOR));
+}
+
+
+int arg_parse(int argc, char * *argv, void * *argtable)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    struct arg_end *endtable;
+    int endindex;
+    char * *argvcopy = NULL;
+
+    /*printf("arg_parse(%d,%p,%p)\n",argc,argv,argtable);*/
+
+    /* reset any argtable data from previous invocations */
+    arg_reset(argtable);
+
+    /* locate the first end-of-table marker within the array */
+    endindex = arg_endindex(table);
+    endtable = (struct arg_end *)table[endindex];
+
+    /* Special case of argc==0.  This can occur on Texas Instruments DSP. */
+    /* Failure to trap this case results in an unwanted NULL result from  */
+    /* the malloc for argvcopy (next code block).                         */
+    if (argc == 0)
+    {
+        /* We must still perform post-parse checks despite the absence of command line arguments */
+        arg_parse_check(table, endtable);
+
+        /* Now we are finished */
+        return endtable->count;
+    }
+
+    argvcopy = (char **)malloc(sizeof(char *) * (argc + 1));
+    if (argvcopy)
+    {
+        int i;
+
+        /*
+           Fill in the local copy of argv[]. We need a local copy
+           because getopt rearranges argv[] which adversely affects
+           susbsequent parsing attempts.
+         */
+        for (i = 0; i < argc; i++)
+            argvcopy[i] = argv[i];
+
+        argvcopy[argc] = NULL;
+        
+        /* parse the command line (local copy) for tagged options */
+        arg_parse_tagged(argc, argvcopy, table, endtable);
+
+        /* parse the command line (local copy) for untagged options */
+        arg_parse_untagged(argc, argvcopy, table, endtable);
+
+        /* if no errors so far then perform post-parse checks otherwise dont bother */
+        if (endtable->count == 0)
+            arg_parse_check(table, endtable);
+
+        /* release the local copt of argv[] */
+        free(argvcopy);
+    }
+    else
+    {
+        /* memory alloc failed */
+        arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
+    }
+
+    return endtable->count;
+}
+
+
+/*
+ * Concatenate contents of src[] string onto *pdest[] string.
+ * The *pdest pointer is altered to point to the end of the
+ * target string and *pndest is decremented by the same number
+ * of chars.
+ * Does not append more than *pndest chars into *pdest[]
+ * so as to prevent buffer overruns.
+ * Its something like strncat() but more efficient for repeated
+ * calls on the same destination string.
+ * Example of use:
+ *   char dest[30] = "good"
+ *   size_t ndest = sizeof(dest);
+ *   char *pdest = dest;
+ *   arg_char(&pdest,"bye ",&ndest);
+ *   arg_char(&pdest,"cruel ",&ndest);
+ *   arg_char(&pdest,"world!",&ndest);
+ * Results in:
+ *   dest[] == "goodbye cruel world!"
+ *   ndest  == 10
+ */
+static
+void arg_cat(char * *pdest, const char *src, size_t *pndest)
+{
+    char *dest = *pdest;
+    char *end  = dest + *pndest;
+
+    /*locate null terminator of dest string */
+    while(dest < end && *dest != 0)
+        dest++;
+
+    /* concat src string to dest string */
+    while(dest < end && *src != 0)
+        *dest++ = *src++;
+
+    /* null terminate dest string */
+    *dest = 0;
+
+    /* update *pdest and *pndest */
+    *pndest = end - dest;
+    *pdest  = dest;
+}
+
+
+static
+void arg_cat_option(char *dest,
+                    size_t ndest,
+                    const char *shortopts,
+                    const char *longopts,
+                    const char *datatype,
+                    int optvalue)
+{
+    if (shortopts)
+    {
+        char option[3];
+
+        /* note: option array[] is initialiazed dynamically here to satisfy   */
+        /* a deficiency in the watcom compiler wrt static array initializers. */
+        option[0] = '-';
+        option[1] = shortopts[0];
+        option[2] = 0;
+
+        arg_cat(&dest, option, &ndest);
+        if (datatype)
+        {
+            arg_cat(&dest, " ", &ndest);
+            if (optvalue)
+            {
+                arg_cat(&dest, "[", &ndest);
+                arg_cat(&dest, datatype, &ndest);
+                arg_cat(&dest, "]", &ndest);
+            }
+            else
+                arg_cat(&dest, datatype, &ndest);
+        }
+    }
+    else if (longopts)
+    {
+        size_t ncspn;
+
+        /* add "--" tag prefix */
+        arg_cat(&dest, "--", &ndest);
+
+        /* add comma separated option tag */
+        ncspn = strcspn(longopts, ",");
+        strncat(dest, longopts, (ncspn < ndest) ? ncspn : ndest);
+
+        if (datatype)
+        {
+            arg_cat(&dest, "=", &ndest);
+            if (optvalue)
+            {
+                arg_cat(&dest, "[", &ndest);
+                arg_cat(&dest, datatype, &ndest);
+                arg_cat(&dest, "]", &ndest);
+            }
+            else
+                arg_cat(&dest, datatype, &ndest);
+        }
+    }
+    else if (datatype)
+    {
+        if (optvalue)
+        {
+            arg_cat(&dest, "[", &ndest);
+            arg_cat(&dest, datatype, &ndest);
+            arg_cat(&dest, "]", &ndest);
+        }
+        else
+            arg_cat(&dest, datatype, &ndest);
+    }
+}
+
+static
+void arg_cat_optionv(char *dest,
+                     size_t ndest,
+                     const char *shortopts,
+                     const char *longopts,
+                     const char *datatype,
+                     int optvalue,
+                     const char *separator)
+{
+    separator = separator ? separator : "";
+
+    if (shortopts)
+    {
+        const char *c = shortopts;
+        while(*c)
+        {
+            /* "-a|-b|-c" */
+            char shortopt[3];
+
+            /* note: shortopt array[] is initialiazed dynamically here to satisfy */
+            /* a deficiency in the watcom compiler wrt static array initializers. */
+            shortopt[0] = '-';
+            shortopt[1] = *c;
+            shortopt[2] = 0;
+
+            arg_cat(&dest, shortopt, &ndest);
+            if (*++c)
+                arg_cat(&dest, separator, &ndest);
+        }
+    }
+
+    /* put separator between long opts and short opts */
+    if (shortopts && longopts)
+        arg_cat(&dest, separator, &ndest);
+
+    if (longopts)
+    {
+        const char *c = longopts;
+        while(*c)
+        {
+            size_t ncspn;
+
+            /* add "--" tag prefix */
+            arg_cat(&dest, "--", &ndest);
+
+            /* add comma separated option tag */
+            ncspn = strcspn(c, ",");
+            strncat(dest, c, (ncspn < ndest) ? ncspn : ndest);
+            c += ncspn;
+
+            /* add given separator in place of comma */
+            if (*c == ',')
+            {
+                arg_cat(&dest, separator, &ndest);
+                c++;
+            }
+        }
+    }
+
+    if (datatype)
+    {
+        if (longopts)
+            arg_cat(&dest, "=", &ndest);
+        else if (shortopts)
+            arg_cat(&dest, " ", &ndest);
+
+        if (optvalue)
+        {
+            arg_cat(&dest, "[", &ndest);
+            arg_cat(&dest, datatype, &ndest);
+            arg_cat(&dest, "]", &ndest);
+        }
+        else
+            arg_cat(&dest, datatype, &ndest);
+    }
+}
+
+
+/* this function should be deprecated because it doesnt consider optional argument values (ARG_HASOPTVALUE) */
+void arg_print_option(FILE *fp,
+                      const char *shortopts,
+                      const char *longopts,
+                      const char *datatype,
+                      const char *suffix)
+{
+    char syntax[200] = "";
+    suffix = suffix ? suffix : "";
+
+    /* there is no way of passing the proper optvalue for optional argument values here, so we must ignore it */
+    arg_cat_optionv(syntax,
+                    sizeof(syntax),
+                    shortopts,
+                    longopts,
+                    datatype,
+                    0,
+                    "|");
+
+    fputs(syntax, fp);
+    fputs(suffix, fp);
+}
+
+
+/*
+ * Print a GNU style [OPTION] string in which all short options that
+ * do not take argument values are presented in abbreviated form, as
+ * in: -xvfsd, or -xvf[sd], or [-xvsfd]
+ */
+static
+void arg_print_gnuswitch(FILE *fp, struct arg_hdr * *table)
+{
+    int tabindex;
+    char *format1 = " -%c";
+    char *format2 = " [-%c";
+    char *suffix = "";
+
+    /* print all mandatory switches that are without argument values */
+    for(tabindex = 0;
+        table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+        tabindex++)
+    {
+        /* skip optional options */
+        if (table[tabindex]->mincount < 1)
+            continue;
+
+        /* skip non-short options */
+        if (table[tabindex]->shortopts == NULL)
+            continue;
+
+        /* skip options that take argument values */
+        if (table[tabindex]->flag & ARG_HASVALUE)
+            continue;
+
+        /* print the short option (only the first short option char, ignore multiple choices)*/
+        fprintf(fp, format1, table[tabindex]->shortopts[0]);
+        format1 = "%c";
+        format2 = "[%c";
+    }
+
+    /* print all optional switches that are without argument values */
+    for(tabindex = 0;
+        table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+        tabindex++)
+    {
+        /* skip mandatory args */
+        if (table[tabindex]->mincount > 0)
+            continue;
+
+        /* skip args without short options */
+        if (table[tabindex]->shortopts == NULL)
+            continue;
+
+        /* skip args with values */
+        if (table[tabindex]->flag & ARG_HASVALUE)
+            continue;
+
+        /* print first short option */
+        fprintf(fp, format2, table[tabindex]->shortopts[0]);
+        format2 = "%c";
+        suffix = "]";
+    }
+
+    fprintf(fp, "%s", suffix);
+}
+
+
+void arg_print_syntax(FILE *fp, void * *argtable, const char *suffix)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int i, tabindex;
+
+    /* print GNU style [OPTION] string */
+    arg_print_gnuswitch(fp, table);
+
+    /* print remaining options in abbreviated style */
+    for(tabindex = 0;
+        table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+        tabindex++)
+    {
+        char syntax[200] = "";
+        const char *shortopts, *longopts, *datatype;
+
+        /* skip short options without arg values (they were printed by arg_print_gnu_switch) */
+        if (table[tabindex]->shortopts &&
+            !(table[tabindex]->flag & ARG_HASVALUE))
+            continue;
+
+        shortopts = table[tabindex]->shortopts;
+        longopts  = table[tabindex]->longopts;
+        datatype  = table[tabindex]->datatype;
+        arg_cat_option(syntax,
+                       sizeof(syntax),
+                       shortopts,
+                       longopts,
+                       datatype,
+                       table[tabindex]->flag & ARG_HASOPTVALUE);
+
+        if (strlen(syntax) > 0)
+        {
+            /* print mandatory instances of this option */
+            for (i = 0; i < table[tabindex]->mincount; i++)
+                fprintf(fp, " %s", syntax);
+
+            /* print optional instances enclosed in "[..]" */
+            switch ( table[tabindex]->maxcount - table[tabindex]->mincount )
+            {
+            case 0:
+                break;
+            case 1:
+                fprintf(fp, " [%s]", syntax);
+                break;
+            case 2:
+                fprintf(fp, " [%s] [%s]", syntax, syntax);
+                break;
+            default:
+                fprintf(fp, " [%s]...", syntax);
+                break;
+            }
+        }
+    }
+
+    if (suffix)
+        fprintf(fp, "%s", suffix);
+}
+
+
+void arg_print_syntaxv(FILE *fp, void * *argtable, const char *suffix)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int i, tabindex;
+
+    /* print remaining options in abbreviated style */
+    for(tabindex = 0;
+        table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+        tabindex++)
+    {
+        char syntax[200] = "";
+        const char *shortopts, *longopts, *datatype;
+
+        shortopts = table[tabindex]->shortopts;
+        longopts  = table[tabindex]->longopts;
+        datatype  = table[tabindex]->datatype;
+        arg_cat_optionv(syntax,
+                        sizeof(syntax),
+                        shortopts,
+                        longopts,
+                        datatype,
+                        table[tabindex]->flag & ARG_HASOPTVALUE,
+                        "|");
+
+        /* print mandatory options */
+        for (i = 0; i < table[tabindex]->mincount; i++)
+            fprintf(fp, " %s", syntax);
+
+        /* print optional args enclosed in "[..]" */
+        switch ( table[tabindex]->maxcount - table[tabindex]->mincount )
+        {
+        case 0:
+            break;
+        case 1:
+            fprintf(fp, " [%s]", syntax);
+            break;
+        case 2:
+            fprintf(fp, " [%s] [%s]", syntax, syntax);
+            break;
+        default:
+            fprintf(fp, " [%s]...", syntax);
+            break;
+        }
+    }
+
+    if (suffix)
+        fprintf(fp, "%s", suffix);
+}
+
+
+void arg_print_glossary(FILE *fp, void * *argtable, const char *format)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int tabindex;
+
+    format = format ? format : "  %-20s %s\n";
+    for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+    {
+        if (table[tabindex]->glossary)
+        {
+            char syntax[200] = "";
+            const char *shortopts = table[tabindex]->shortopts;
+            const char *longopts  = table[tabindex]->longopts;
+            const char *datatype  = table[tabindex]->datatype;
+            const char *glossary  = table[tabindex]->glossary;
+            arg_cat_optionv(syntax,
+                            sizeof(syntax),
+                            shortopts,
+                            longopts,
+                            datatype,
+                            table[tabindex]->flag & ARG_HASOPTVALUE,
+                            ", ");
+            fprintf(fp, format, syntax, glossary);
+        }
+    }
+}
+
+
+/**
+ * Print a piece of text formatted, which means in a column with a
+ * left and a right margin. The lines are wrapped at whitspaces next
+ * to right margin. The function does not indent the first line, but
+ * only the following ones.
+ *
+ * Example:
+ * arg_print_formatted( fp, 0, 5, "Some text that doesn't fit." )
+ * will result in the following output:
+ *
+ * Some
+ * text
+ * that
+ * doesn'
+ * t fit.
+ *
+ * Too long lines will be wrapped in the middle of a word.
+ *
+ * arg_print_formatted( fp, 2, 7, "Some text that doesn't fit." )
+ * will result in the following output:
+ *
+ * Some
+ *   text
+ *   that
+ *   doesn'
+ *   t fit.
+ *
+ * As you see, the first line is not indented. This enables output of
+ * lines, which start in a line where output already happened.
+ *
+ * Author: Uli Fouquet
+ */
+static
+void arg_print_formatted( FILE *fp,
+                          const unsigned lmargin,
+                          const unsigned rmargin,
+                          const char *text )
+{
+    const unsigned textlen = strlen( text );
+    unsigned line_start = 0;
+    unsigned line_end = textlen + 1;
+    const unsigned colwidth = (rmargin - lmargin) + 1;
+
+    /* Someone doesn't like us... */
+    if ( line_end < line_start )
+    { fprintf( fp, "%s\n", text ); }
+
+    while (line_end - 1 > line_start )
+    {
+        /* Eat leading whitespaces. This is essential because while
+           wrapping lines, there will often be a whitespace at beginning
+           of line */
+        while ( isspace(*(text + line_start)) )
+        { line_start++; }
+
+        if ((line_end - line_start) > colwidth )
+        { line_end = line_start + colwidth; }
+
+        /* Find last whitespace, that fits into line */
+        while ( ( line_end > line_start )
+                && ( line_end - line_start > colwidth )
+                && !isspace(*(text + line_end)))
+        { line_end--; }
+
+        /* Do not print trailing whitespace. If this text
+           has got only one line, line_end now points to the
+           last char due to initialization. */
+        line_end--;
+
+        /* Output line of text */
+        while ( line_start < line_end )
+        {
+            fputc(*(text + line_start), fp );
+            line_start++;
+        }
+        fputc( '\n', fp );
+
+        /* Initialize another line */
+        if ( line_end + 1 < textlen )
+        {
+            unsigned i;
+
+            for (i = 0; i < lmargin; i++ )
+            { fputc( ' ', fp ); }
+
+            line_end = textlen;
+        }
+
+        /* If we have to print another line, get also the last char. */
+        line_end++;
+
+    } /* lines of text */
+}
+
+/**
+ * Prints the glossary in strict GNU format.
+ * Differences to arg_print_glossary() are:
+ *   - wraps lines after 80 chars
+ *   - indents lines without shortops
+ *   - does not accept formatstrings
+ *
+ * Contributed by Uli Fouquet
+ */
+void arg_print_glossary_gnu(FILE *fp, void * *argtable )
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int tabindex;
+
+    for(tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++)
+    {
+        if (table[tabindex]->glossary)
+        {
+            char syntax[200] = "";
+            const char *shortopts = table[tabindex]->shortopts;
+            const char *longopts  = table[tabindex]->longopts;
+            const char *datatype  = table[tabindex]->datatype;
+            const char *glossary  = table[tabindex]->glossary;
+
+            if ( !shortopts && longopts )
+            {
+                /* Indent trailing line by 4 spaces... */
+                memset( syntax, ' ', 4 );
+                *(syntax + 4) = '\0';
+            }
+
+            arg_cat_optionv(syntax,
+                            sizeof(syntax),
+                            shortopts,
+                            longopts,
+                            datatype,
+                            table[tabindex]->flag & ARG_HASOPTVALUE,
+                            ", ");
+
+            /* If syntax fits not into column, print glossary in new line... */
+            if ( strlen(syntax) > 25 )
+            {
+                fprintf( fp, "  %-25s %s\n", syntax, "" );
+                *syntax = '\0';
+            }
+
+            fprintf( fp, "  %-25s ", syntax );
+            arg_print_formatted( fp, 28, 79, glossary );
+        }
+    } /* for each table entry */
+
+    fputc( '\n', fp );
+}
+
+
+/**
+ * Checks the argtable[] array for NULL entries and returns 1
+ * if any are found, zero otherwise.
+ */
+int arg_nullcheck(void * *argtable)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int tabindex;
+    /*printf("arg_nullcheck(%p)\n",argtable);*/
+
+    if (!table)
+        return 1;
+
+    tabindex = 0;
+    do
+    {
+        /*printf("argtable[%d]=%p\n",tabindex,argtable[tabindex]);*/
+        if (!table[tabindex])
+            return 1;
+    } while(!(table[tabindex++]->flag & ARG_TERMINATOR));
+
+    return 0;
+}
+
+
+/*
+ * arg_free() is deprecated in favour of arg_freetable() due to a flaw in its design.
+ * The flaw results in memory leak in the (very rare) case that an intermediate
+ * entry in the argtable array failed its memory allocation while others following
+ * that entry were still allocated ok. Those subsequent allocations will not be
+ * deallocated by arg_free().
+ * Despite the unlikeliness of the problem occurring, and the even unlikelier event
+ * that it has any deliterious effect, it is fixed regardless by replacing arg_free()
+ * with the newer arg_freetable() function.
+ * We still keep arg_free() for backwards compatibility.
+ */
+void arg_free(void * *argtable)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    int tabindex = 0;
+    int flag;
+    /*printf("arg_free(%p)\n",argtable);*/
+    do
+    {
+        /*
+           if we encounter a NULL entry then somewhat incorrectly we presume
+           we have come to the end of the array. It isnt strictly true because
+           an intermediate entry could be NULL with other non-NULL entries to follow.
+           The subsequent argtable entries would then not be freed as they should.
+         */
+        if (table[tabindex] == NULL)
+            break;
+
+        flag = table[tabindex]->flag;
+        free(table[tabindex]);
+        table[tabindex++] = NULL;
+
+    } while(!(flag & ARG_TERMINATOR));
+}
+
+/* frees each non-NULL element of argtable[], where n is the size of the number of entries in the array */
+void arg_freetable(void * *argtable, size_t n)
+{
+    struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+    size_t tabindex = 0;
+    /*printf("arg_freetable(%p)\n",argtable);*/
+    for (tabindex = 0; tabindex < n; tabindex++)
+    {
+        if (table[tabindex] == NULL)
+            continue;
+
+        free(table[tabindex]);
+        table[tabindex] = NULL;
+    };
+}
+
diff --git a/components/console/argtable3/argtable3.h b/components/console/argtable3/argtable3.h
new file mode 100644 (file)
index 0000000..1107de2
--- /dev/null
@@ -0,0 +1,305 @@
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ * <sheitmann@users.sourceforge.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of STEWART HEITMANN nor the  names of its contributors
+ *       may be used to endorse or promote products derived from this software
+ *       without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#ifndef ARGTABLE3
+#define ARGTABLE3
+
+#include <stdio.h>      /* FILE */
+#include <time.h>       /* struct tm */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ARG_REX_ICASE 1
+    
+/* bit masks for arg_hdr.flag */
+enum
+{
+    ARG_TERMINATOR=0x1,
+    ARG_HASVALUE=0x2,
+    ARG_HASOPTVALUE=0x4
+};
+
+typedef void (arg_resetfn)(void *parent);
+typedef int  (arg_scanfn)(void *parent, const char *argval);
+typedef int  (arg_checkfn)(void *parent);
+typedef void (arg_errorfn)(void *parent, FILE *fp, int error, const char *argval, const char *progname);
+
+
+/*
+* The arg_hdr struct defines properties that are common to all arg_xxx structs.
+* The argtable library requires each arg_xxx struct to have an arg_hdr
+* struct as its first data member.
+* The argtable library functions then use this data to identify the
+* properties of the command line option, such as its option tags,
+* datatype string, and glossary strings, and so on.
+* Moreover, the arg_hdr struct contains pointers to custom functions that
+* are provided by each arg_xxx struct which perform the tasks of parsing
+* that particular arg_xxx arguments, performing post-parse checks, and
+* reporting errors.
+* These functions are private to the individual arg_xxx source code
+* and are the pointer to them are initiliased by that arg_xxx struct's
+* constructor function. The user could alter them after construction
+* if desired, but the original intention is for them to be set by the
+* constructor and left unaltered.
+*/
+struct arg_hdr
+{
+    char         flag;        /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
+    const char  *shortopts;   /* String defining the short options */
+    const char  *longopts;    /* String defiing the long options */
+    const char  *datatype;    /* Description of the argument data type */
+    const char  *glossary;    /* Description of the option as shown by arg_print_glossary function */
+    int          mincount;    /* Minimum number of occurences of this option accepted */
+    int          maxcount;    /* Maximum number of occurences if this option accepted */
+    void        *parent;      /* Pointer to parent arg_xxx struct */
+    arg_resetfn *resetfn;     /* Pointer to parent arg_xxx reset function */
+    arg_scanfn  *scanfn;      /* Pointer to parent arg_xxx scan function */
+    arg_checkfn *checkfn;     /* Pointer to parent arg_xxx check function */
+    arg_errorfn *errorfn;     /* Pointer to parent arg_xxx error function */
+    void        *priv;        /* Pointer to private header data for use by arg_xxx functions */
+};
+
+struct arg_rem
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+};
+
+struct arg_lit
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args */
+};
+
+struct arg_int
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args */
+    int *ival;               /* Array of parsed argument values */
+};
+
+struct arg_dbl
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args */
+    double *dval;            /* Array of parsed argument values */
+};
+
+struct arg_str
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args */
+    const char **sval;       /* Array of parsed argument values */
+};
+
+struct arg_rex
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args */
+    const char **sval;       /* Array of parsed argument values */
+};
+
+struct arg_file
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of matching command line args*/
+    const char **filename;   /* Array of parsed filenames  (eg: /home/foo.bar) */
+    const char **basename;   /* Array of parsed basenames  (eg: foo.bar) */
+    const char **extension;  /* Array of parsed extensions (eg: .bar) */
+};
+
+struct arg_date
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    const char *format;      /* strptime format string used to parse the date */
+    int count;               /* Number of matching command line args */
+    struct tm *tmval;        /* Array of parsed time values */
+};
+
+enum {ARG_ELIMIT=1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG};
+struct arg_end
+{
+    struct arg_hdr hdr;      /* The mandatory argtable header struct */
+    int count;               /* Number of errors encountered */
+    int *error;              /* Array of error codes */
+    void **parent;           /* Array of pointers to offending arg_xxx struct */
+    const char **argval;     /* Array of pointers to offending argv[] string */
+};
+
+
+/**** arg_xxx constructor functions *********************************/
+
+struct arg_rem* arg_rem(const char* datatype, const char* glossary);
+
+struct arg_lit* arg_lit0(const char* shortopts,
+    const char* longopts,
+    const char* glossary);
+struct arg_lit* arg_lit1(const char* shortopts,
+    const char* longopts,
+    const char *glossary);
+struct arg_lit* arg_litn(const char* shortopts,
+    const char* longopts,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_key* arg_key0(const char* keyword,
+    int flags,
+    const char* glossary);
+struct arg_key* arg_key1(const char* keyword,
+    int flags,
+    const char* glossary);
+struct arg_key* arg_keyn(const char* keyword,
+    int flags,
+    int mincount,
+    int maxcount,
+    const char* glossary);
+
+struct arg_int* arg_int0(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char* glossary);
+struct arg_int* arg_int1(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char *glossary);
+struct arg_int* arg_intn(const char* shortopts,
+    const char* longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_dbl* arg_dbl0(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char* glossary);
+struct arg_dbl* arg_dbl1(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char *glossary);
+struct arg_dbl* arg_dbln(const char* shortopts,
+    const char* longopts,
+    const char *datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_str* arg_str0(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char* glossary);
+struct arg_str* arg_str1(const char* shortopts,
+    const char* longopts,                    
+    const char* datatype,
+    const char *glossary);
+struct arg_str* arg_strn(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_rex* arg_rex0(const char* shortopts,
+    const char* longopts,
+    const char* pattern,
+    const char* datatype,
+    int flags,
+    const char* glossary);
+struct arg_rex* arg_rex1(const char* shortopts,
+    const char* longopts,
+    const char* pattern,
+    const char* datatype,
+    int flags,
+    const char *glossary);
+struct arg_rex* arg_rexn(const char* shortopts,
+    const char* longopts,
+    const char* pattern,
+    const char* datatype,
+    int mincount,
+    int maxcount,
+    int flags,
+    const char *glossary);
+
+struct arg_file* arg_file0(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char* glossary);
+struct arg_file* arg_file1(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    const char *glossary);
+struct arg_file* arg_filen(const char* shortopts,
+    const char* longopts,
+    const char* datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_date* arg_date0(const char* shortopts,
+    const char* longopts,
+    const char* format,
+    const char* datatype,
+    const char* glossary);
+struct arg_date* arg_date1(const char* shortopts,
+    const char* longopts,
+    const char* format,
+    const char* datatype,
+    const char *glossary);
+struct arg_date* arg_daten(const char* shortopts,
+    const char* longopts,
+    const char* format,
+    const char* datatype,
+    int mincount,
+    int maxcount,
+    const char *glossary);
+
+struct arg_end* arg_end(int maxerrors);
+
+
+/**** other functions *******************************************/
+int arg_nullcheck(void **argtable);
+int arg_parse(int argc, char **argv, void **argtable);
+void arg_print_option(FILE *fp, const char *shortopts, const char *longopts, const char *datatype, const char *suffix);
+void arg_print_syntax(FILE *fp, void **argtable, const char *suffix);
+void arg_print_syntaxv(FILE *fp, void **argtable, const char *suffix);
+void arg_print_glossary(FILE *fp, void **argtable, const char *format);
+void arg_print_glossary_gnu(FILE *fp, void **argtable);
+void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname);
+void arg_freetable(void **argtable, size_t n);
+
+/**** deprecated functions, for back-compatibility only ********/
+void arg_free(void **argtable);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/components/console/commands.c b/components/console/commands.c
new file mode 100644 (file)
index 0000000..a451584
--- /dev/null
@@ -0,0 +1,234 @@
+// Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/param.h>
+#include "esp_log.h"
+#include "esp_console.h"
+#include "linenoise/linenoise.h"
+#include "argtable3/argtable3.h"
+#include "rom/queue.h"
+
+#define ANSI_COLOR_DEFAULT      39      /** Default foreground color */
+
+typedef struct cmd_item_ {
+    /**
+     * Command name (statically allocated by application)
+     */
+    const char* command;
+    /**
+     * Help text (statically allocated by application), may be NULL.
+     */
+    const char* help;
+    /**
+     * Hint text, usually lists possible arguments, dynamically allocated.
+     * May be NULL.
+     */
+    char* hint;
+    esp_console_cmd_func_t func;    //!< pointer to the command handler
+    void* argtable;                 //!< optional pointer to arg table
+    SLIST_ENTRY(cmd_item_) next;    //!< next command in the list
+} cmd_item_t;
+
+/** linked list of command structures */
+static SLIST_HEAD(cmd_list_, cmd_item_) s_cmd_list;
+
+/** run-time configuration options */
+static esp_console_config_t s_config;
+
+/** temporary buffer used for command line parsing */
+static char* s_tmp_line_buf;
+
+static const cmd_item_t* find_command_by_name(const char* name);
+
+esp_err_t esp_console_init(const esp_console_config_t* config)
+{
+    if (s_tmp_line_buf) {
+        return ESP_ERR_INVALID_STATE;
+    }
+    memcpy(&s_config, config, sizeof(s_config));
+    if (s_config.hint_color == 0) {
+        s_config.hint_color = ANSI_COLOR_DEFAULT;
+    }
+    s_tmp_line_buf = calloc(config->max_cmdline_length, 1);
+    if (s_tmp_line_buf == NULL) {
+        return ESP_ERR_NO_MEM;
+    }
+    return ESP_OK;
+}
+
+esp_err_t esp_console_deinit()
+{
+    if (!s_tmp_line_buf) {
+        return ESP_ERR_INVALID_STATE;
+    }
+    free(s_tmp_line_buf);
+    cmd_item_t *it, *tmp;
+    SLIST_FOREACH_SAFE(it, &s_cmd_list, next, tmp) {
+        free(it->hint);
+        free(it);
+    }
+    return ESP_OK;
+}
+
+esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd)
+{
+    cmd_item_t *item = (cmd_item_t *) calloc(1, sizeof(*item));
+    if (item == NULL) {
+        return ESP_ERR_NO_MEM;
+    }
+    if (cmd->command == NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    if (strchr(cmd->command, ' ') != NULL) {
+        return ESP_ERR_INVALID_ARG;
+    }
+    item->command = cmd->command;
+    item->help = cmd->help;
+    if (cmd->hint) {
+        /* Prepend a space before the hint. It separates command name and
+         * the hint. arg_print_syntax below adds this space as well.
+         */
+        asprintf(&item->hint, " %s", cmd->hint);
+    } else if (cmd->argtable) {
+        /* Generate hint based on cmd->argtable */
+        char* buf;
+        size_t buf_size;
+        FILE* f = open_memstream(&buf, &buf_size);
+        arg_print_syntax(f, cmd->argtable, NULL);
+        fclose(f);
+        item->hint = buf;
+    }
+    item->argtable = cmd->argtable;
+    item->func = cmd->func;
+    cmd_item_t* last = SLIST_FIRST(&s_cmd_list);
+    if (last == NULL) {
+        SLIST_INSERT_HEAD(&s_cmd_list, item, next);
+    } else {
+        cmd_item_t* it;
+        while ((it = SLIST_NEXT(last, next)) != NULL) {
+            last = it;
+        }
+        SLIST_INSERT_AFTER(last, item, next);
+    }
+    return ESP_OK;
+}
+
+void esp_console_get_completion(const char *buf, linenoiseCompletions *lc)
+{
+    size_t len = strlen(buf);
+    if (len == 0) {
+        return;
+    }
+    cmd_item_t* it;
+    SLIST_FOREACH(it, &s_cmd_list, next) {
+        /* Check if command starts with buf */
+        if (strncmp(buf, it->command, len) == 0) {
+            linenoiseAddCompletion(lc, it->command);
+        }
+    }
+}
+
+const char* esp_console_get_hint(const char *buf, int *color, int *bold)
+{
+    int len = strlen(buf);
+    cmd_item_t* it;
+    SLIST_FOREACH(it, &s_cmd_list, next) {
+        if (strlen(it->command) == len &&
+                strncmp(buf, it->command, len) == 0) {
+            *color = s_config.hint_color;
+            *bold = s_config.hint_bold;
+            return it->hint;
+        }
+    }
+    return NULL;
+}
+
+static const cmd_item_t* find_command_by_name(const char* name)
+{
+    const cmd_item_t* cmd = NULL;
+    cmd_item_t* it;
+    SLIST_FOREACH(it, &s_cmd_list, next) {
+        if (strcmp(name, it->command) == 0) {
+            cmd = it;
+            break;
+        }
+    }
+    return cmd;
+}
+
+esp_err_t esp_console_run(const char* cmdline, int* cmd_ret)
+{
+    if (s_tmp_line_buf == NULL) {
+        return ESP_ERR_INVALID_STATE;
+    }
+    char** argv = (char**) calloc(s_config.max_cmdline_args, sizeof(char*));
+    if (argv == NULL) {
+        return ESP_ERR_NO_MEM;
+    }
+    strlcpy(s_tmp_line_buf, cmdline, s_config.max_cmdline_length);
+
+    size_t argc = esp_console_split_argv(s_tmp_line_buf, argv,
+            s_config.max_cmdline_args);
+
+    const cmd_item_t* cmd = find_command_by_name(argv[0]);
+    if (cmd == NULL) {
+        return ESP_ERR_NOT_FOUND;
+    }
+    *cmd_ret = (*cmd->func)(argc, argv);
+    free(argv);
+    return ESP_OK;
+}
+
+static int help_command(int argc, char** argv)
+{
+    cmd_item_t* it;
+
+    /* Print summary of each command */
+    SLIST_FOREACH(it, &s_cmd_list, next) {
+        if (it->help == NULL) {
+            continue;
+        }
+        /* First line: command name and hint
+         * Pad all the hints to the same column
+         */
+        const char* hint = (it->hint) ? it->hint : "";
+        printf("%-s %s\n", it->command, hint);
+        /* Second line: print help.
+         * Argtable has a nice helper function for this which does line
+         * wrapping.
+         */
+        printf("  "); // arg_print_formatted does not indent the first line
+        arg_print_formatted(stdout, 2, 78, it->help);
+        /* Finally, print the list of arguments */
+        if (it->argtable) {
+            arg_print_glossary(stdout, (void**) it->argtable, "  %12s  %s\n");
+        }
+        printf("\n");
+    }
+    return 0;
+}
+
+
+esp_err_t esp_console_register_help_command()
+{
+    esp_console_cmd_t command = {
+            .command = "help",
+            .help = "Print the list of registered commands",
+            .func = &help_command
+    };
+    return esp_console_cmd_register(&command);
+}
diff --git a/components/console/component.mk b/components/console/component.mk
new file mode 100644 (file)
index 0000000..0a6d494
--- /dev/null
@@ -0,0 +1,2 @@
+COMPONENT_ADD_INCLUDEDIRS := .
+COMPONENT_SRCDIRS := linenoise argtable3 .
diff --git a/components/console/esp_console.h b/components/console/esp_console.h
new file mode 100644 (file)
index 0000000..17cf5fe
--- /dev/null
@@ -0,0 +1,181 @@
+// Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+#pragma once
+
+#include <stddef.h>
+#include "esp_err.h"
+
+// Forward declaration. Definition in linenoise/linenoise.h.
+typedef struct linenoiseCompletions linenoiseCompletions;
+
+/**
+ * @brief Parameters for console initialization
+ */
+typedef struct {
+    size_t max_cmdline_length;  //!< length of command line buffer, in bytes
+    size_t max_cmdline_args;    //!< maximum number of command line arguments to parse
+    int hint_color;     //!< ASCII color code of hint text
+    int hint_bold;      //!< Set to 1 to print hint text in bold
+} esp_console_config_t;
+
+/**
+ * @brief initialize console module
+ * Call this once before using other console module features
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_NO_MEM if out of memory
+ *      - ESP_ERR_INVALID_STATE if already initialized
+ */
+esp_err_t esp_console_init(const esp_console_config_t* config);
+
+
+/**
+ * @brief de-initialize console module
+ * Call this once when done using console module functions
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_STATE if not initialized yet
+ */
+esp_err_t esp_console_deinit();
+
+
+/**
+ * @brief Console command main function
+ * @param argc number of arguments
+ * @param argv array with argc entries, each pointing to a zero-terminated string argument
+ * @return console command return code, 0 indicates "success"
+ */
+typedef int (*esp_console_cmd_func_t)(int argc, char** argv);
+
+/**
+ * @brief Console command description
+ */
+typedef struct {
+    /**
+     * Command name. Must not be NULL, must not contain spaces.
+     * The pointer must be valid until the call to esp_console_deinit.
+     */
+    const char* command;    //!< command name
+    /**
+     * Help text for the command, shown by help command.
+     * If set, the pointer must be valid until the call to esp_console_deinit.
+     * If not set, the command will not be listed in 'help' output.
+     */
+    const char* help;
+    /**
+     * Hint text, usually lists possible arguments.
+     * If set to NULL, and 'argtable' field is non-NULL, hint will be generated
+     * automatically
+     */
+    const char* hint;
+    /**
+     * Pointer to a function which implements the command.
+     */
+    esp_console_cmd_func_t func;
+    /**
+     * Array or structure of pointers to arg_xxx structures, may be NULL.
+     * Used to generate hint text if 'hint' is set to NULL.
+     * Array/structure which this field points to must end with an arg_end.
+     * Only used for the duration of esp_console_cmd_register call.
+     */
+    void* argtable;
+} esp_console_cmd_t;
+
+/**
+ * @brief Register console command
+ * @param cmd pointer to the command description; can point to a temporary value
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_NO_MEM if out of memory
+ */
+esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd);
+
+/**
+ * @brief Run command line
+ * @param cmdline command line (command name followed by a number of arguments)
+ * @param[out] cmd_ret return code from the command (set if command was run)
+ * @return
+ *      - ESP_OK, if command was run
+ *      - ESP_ERR_NOT_FOUND, if command with given name wasn't registered
+ *      - ESP_ERR_INVALID_STATE, if esp_console_init wasn't called
+ */
+esp_err_t esp_console_run(const char* cmdline, int* cmd_ret);
+
+/**
+ * @brief Split command line into arguments in place
+ *
+ * - This function finds whitespace-separated arguments in the given input line.
+ *
+ *     'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ]
+ *
+ * - Argument which include spaces may be surrounded with quotes. In this case
+ *   spaces are preserved and quotes are stripped.
+ *
+ *     'abc "123 456" def' -> [ 'abc', '123 456', 'def' ]
+ *
+ * - Escape sequences may be used to produce backslash, double quote, and space:
+ *
+ *     'a\ b\\c\"' -> [ 'a b\c"' ]
+ *
+ * Pointers to at most argv_size - 1 arguments are returned in argv array.
+ * The pointer after the last one (i.e. argv[argc]) is set to NULL.
+ *
+ * @param line pointer to buffer to parse; it is modified in place
+ * @param argv array where the pointers to arguments are written
+ * @param argv_size number of elements in argv_array (max. number of arguments)
+ * @return number of arguments found (argc)
+ */
+size_t esp_console_split_argv(char *line, char **argv, size_t argv_size);
+
+/**
+ * @brief Callback which provides command completion for linenoise library
+ *
+ * When using linenoise for line editing, command completion support
+ * can be enabled like this:
+ *
+ *   linenoiseSetCompletionCallback(&esp_console_get_completion);
+ *
+ * @param buf the string typed by the user
+ * @param lc linenoiseCompletions to be filled in
+ */
+void esp_console_get_completion(const char *buf, linenoiseCompletions *lc);
+
+/**
+ * @brief Callback which provides command hints for linenoise library
+ *
+ * When using linenoise for line editing, hints support can be enabled as
+ * follows:
+ *
+ *   linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
+ *
+ * The extra cast is needed because linenoiseHintsCallback is defined as
+ * returning a char* instead of const char*.
+ *
+ * @param buf line typed by the user
+ * @param[out] color ANSI color code to be used when displaying the hint
+ * @param[out] bold set to 1 if hint has to be displayed in bold
+ * @return string containing the hint text. This string is persistent and should
+ *         not be freed (i.e. linenoiseSetFreeHintsCallback should not be used).
+ */
+const char *esp_console_get_hint(const char *buf, int *color, int *bold);
+
+/**
+ * @brief Register a 'help' command
+ * Default 'help' command prints the list of registered commands along with
+ * hints and help strings.
+ * @return
+ *      - ESP_OK on success
+ *      - ESP_ERR_INVALID_STATE, if esp_console_init wasn't called
+ */
+esp_err_t esp_console_register_help_command();
diff --git a/components/console/linenoise/LICENSE b/components/console/linenoise/LICENSE
new file mode 100644 (file)
index 0000000..18e8148
--- /dev/null
@@ -0,0 +1,25 @@
+Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
+Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice,
+  this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/components/console/linenoise/linenoise.c b/components/console/linenoise/linenoise.c
new file mode 100644 (file)
index 0000000..f68b6ec
--- /dev/null
@@ -0,0 +1,1025 @@
+/* linenoise.c -- guerrilla line editing library against the idea that a
+ * line editing lib needs to be 20,000 lines of C code.
+ *
+ * You can find the latest source code at:
+ *
+ *   http://github.com/antirez/linenoise
+ *
+ * Does a number of crazy assumptions that happen to be true in 99.9999% of
+ * the 2010 UNIX computers around.
+ *
+ * ------------------------------------------------------------------------
+ *
+ * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
+ * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *  *  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *  *  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ------------------------------------------------------------------------
+ *
+ * References:
+ * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+ * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
+ *
+ * Todo list:
+ * - Filter bogus Ctrl+<char> combinations.
+ * - Win32 support
+ *
+ * Bloat:
+ * - History search like Ctrl+r in readline?
+ *
+ * List of escape sequences used by this program, we do everything just
+ * with three sequences. In order to be so cheap we may have some
+ * flickering effect with some slow terminal, but the lesser sequences
+ * the more compatible.
+ *
+ * EL (Erase Line)
+ *    Sequence: ESC [ n K
+ *    Effect: if n is 0 or missing, clear from cursor to end of line
+ *    Effect: if n is 1, clear from beginning of line to cursor
+ *    Effect: if n is 2, clear entire line
+ *
+ * CUF (CUrsor Forward)
+ *    Sequence: ESC [ n C
+ *    Effect: moves cursor forward n chars
+ *
+ * CUB (CUrsor Backward)
+ *    Sequence: ESC [ n D
+ *    Effect: moves cursor backward n chars
+ *
+ * The following is used to get the terminal width if getting
+ * the width with the TIOCGWINSZ ioctl fails
+ *
+ * DSR (Device Status Report)
+ *    Sequence: ESC [ 6 n
+ *    Effect: reports the current cusor position as ESC [ n ; m R
+ *            where n is the row and m is the column
+ *
+ * When multi line mode is enabled, we also use an additional escape
+ * sequence. However multi line editing is disabled by default.
+ *
+ * CUU (Cursor Up)
+ *    Sequence: ESC [ n A
+ *    Effect: moves cursor up of n chars.
+ *
+ * CUD (Cursor Down)
+ *    Sequence: ESC [ n B
+ *    Effect: moves cursor down of n chars.
+ *
+ * When linenoiseClearScreen() is called, two additional escape sequences
+ * are used in order to clear the screen and position the cursor at home
+ * position.
+ *
+ * CUP (Cursor position)
+ *    Sequence: ESC [ H
+ *    Effect: moves the cursor to upper left corner
+ *
+ * ED (Erase display)
+ *    Sequence: ESC [ 2 J
+ *    Effect: clear the whole screen
+ *
+ */
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include "linenoise.h"
+
+#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
+#define LINENOISE_MAX_LINE 4096
+
+static linenoiseCompletionCallback *completionCallback = NULL;
+static linenoiseHintsCallback *hintsCallback = NULL;
+static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
+
+static int mlmode = 0;  /* Multi line mode. Default is single line. */
+static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
+static int history_len = 0;
+static char **history = NULL;
+
+/* The linenoiseState structure represents the state during line editing.
+ * We pass this state to functions implementing specific editing
+ * functionalities. */
+struct linenoiseState {
+    char *buf;          /* Edited line buffer. */
+    size_t buflen;      /* Edited line buffer size. */
+    const char *prompt; /* Prompt to display. */
+    size_t plen;        /* Prompt length. */
+    size_t pos;         /* Current cursor position. */
+    size_t oldpos;      /* Previous refresh cursor position. */
+    size_t len;         /* Current edited line length. */
+    size_t cols;        /* Number of columns in terminal. */
+    size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
+    int history_index;  /* The history index we are currently editing. */
+};
+
+enum KEY_ACTION{
+       KEY_NULL = 0,       /* NULL */
+       CTRL_A = 1,         /* Ctrl+a */
+       CTRL_B = 2,         /* Ctrl-b */
+       CTRL_C = 3,         /* Ctrl-c */
+       CTRL_D = 4,         /* Ctrl-d */
+       CTRL_E = 5,         /* Ctrl-e */
+       CTRL_F = 6,         /* Ctrl-f */
+       CTRL_H = 8,         /* Ctrl-h */
+       TAB = 9,            /* Tab */
+       CTRL_K = 11,        /* Ctrl+k */
+       CTRL_L = 12,        /* Ctrl+l */
+       ENTER = 10,         /* Enter */
+       CTRL_N = 14,        /* Ctrl-n */
+       CTRL_P = 16,        /* Ctrl-p */
+       CTRL_T = 20,        /* Ctrl-t */
+       CTRL_U = 21,        /* Ctrl+u */
+       CTRL_W = 23,        /* Ctrl+w */
+       ESC = 27,           /* Escape */
+       BACKSPACE =  127    /* Backspace */
+};
+
+int linenoiseHistoryAdd(const char *line);
+static void refreshLine(struct linenoiseState *l);
+
+/* Debugging macro. */
+#if 0
+FILE *lndebug_fp = NULL;
+#define lndebug(...) \
+    do { \
+        if (lndebug_fp == NULL) { \
+            lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
+            fprintf(lndebug_fp, \
+            "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
+            (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
+            (int)l->maxrows,old_rows); \
+        } \
+        fprintf(lndebug_fp, ", " __VA_ARGS__); \
+        fflush(lndebug_fp); \
+    } while (0)
+#else
+#define lndebug(fmt, ...)
+#endif
+
+/* ======================= Low level terminal handling ====================== */
+
+/* Set if to use or not the multi line mode. */
+void linenoiseSetMultiLine(int ml) {
+    mlmode = ml;
+}
+
+/* Use the ESC [6n escape sequence to query the horizontal cursor position
+ * and return it. On error -1 is returned, on success the position of the
+ * cursor. */
+static int getCursorPosition() {
+    char buf[32];
+    int cols, rows;
+    unsigned int i = 0;
+
+    /* Report cursor location */
+    fprintf(stdout, "\x1b[6n");
+    /* Read the response: ESC [ rows ; cols R */
+    while (i < sizeof(buf)-1) {
+        if (fread(buf+i, 1, 1, stdin) != 1) break;
+        if (buf[i] == 'R') break;
+        i++;
+    }
+    buf[i] = '\0';
+    /* Parse it. */
+    if (buf[0] != ESC || buf[1] != '[') return -1;
+    if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
+    return cols;
+}
+
+/* Try to get the number of columns in the current terminal, or assume 80
+ * if it fails. */
+static int getColumns() {
+    int start, cols;
+
+    /* Get the initial position so we can restore it later. */
+    start = getCursorPosition();
+    if (start == -1) goto failed;
+
+    /* Go to right margin and get position. */
+    if (fwrite("\x1b[999C", 1, 6, stdout) != 6) goto failed;
+    cols = getCursorPosition();
+    if (cols == -1) goto failed;
+
+    /* Restore position. */
+    if (cols > start) {
+        char seq[32];
+        snprintf(seq,32,"\x1b[%dD",cols-start);
+        if (fwrite(seq, 1, strlen(seq), stdout) == -1) {
+            /* Can't recover... */
+        }
+    }
+    return cols;
+
+failed:
+    return 80;
+}
+
+/* Clear the screen. Used to handle ctrl+l */
+void linenoiseClearScreen(void) {
+    fprintf(stdout,"\x1b[H\x1b[2J");
+}
+
+/* Beep, used for completion when there is nothing to complete or when all
+ * the choices were already shown. */
+static void linenoiseBeep(void) {
+    fprintf(stdout, "\x7");
+}
+
+/* ============================== Completion ================================ */
+
+/* Free a list of completion option populated by linenoiseAddCompletion(). */
+static void freeCompletions(linenoiseCompletions *lc) {
+    size_t i;
+    for (i = 0; i < lc->len; i++)
+        free(lc->cvec[i]);
+    if (lc->cvec != NULL)
+        free(lc->cvec);
+}
+
+/* This is an helper function for linenoiseEdit() and is called when the
+ * user types the <tab> key in order to complete the string currently in the
+ * input.
+ *
+ * The state of the editing is encapsulated into the pointed linenoiseState
+ * structure as described in the structure definition. */
+static int completeLine(struct linenoiseState *ls) {
+    linenoiseCompletions lc = { 0, NULL };
+    int nread, nwritten;
+    char c = 0;
+
+    completionCallback(ls->buf,&lc);
+    if (lc.len == 0) {
+        linenoiseBeep();
+    } else {
+        size_t stop = 0, i = 0;
+
+        while(!stop) {
+            /* Show completion or original buffer */
+            if (i < lc.len) {
+                struct linenoiseState saved = *ls;
+
+                ls->len = ls->pos = strlen(lc.cvec[i]);
+                ls->buf = lc.cvec[i];
+                refreshLine(ls);
+                ls->len = saved.len;
+                ls->pos = saved.pos;
+                ls->buf = saved.buf;
+            } else {
+                refreshLine(ls);
+            }
+
+            nread = fread(&c, 1, 1, stdin);
+            if (nread <= 0) {
+                freeCompletions(&lc);
+                return -1;
+            }
+
+            switch(c) {
+                case TAB: /* tab */
+                    i = (i+1) % (lc.len+1);
+                    if (i == lc.len) linenoiseBeep();
+                    break;
+                case ESC: /* escape */
+                    /* Re-show original buffer */
+                    if (i < lc.len) refreshLine(ls);
+                    stop = 1;
+                    break;
+                default:
+                    /* Update buffer and return */
+                    if (i < lc.len) {
+                        nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
+                        ls->len = ls->pos = nwritten;
+                    }
+                    stop = 1;
+                    break;
+            }
+        }
+    }
+
+    freeCompletions(&lc);
+    return c; /* Return last read character */
+}
+
+/* Register a callback function to be called for tab-completion. */
+void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
+    completionCallback = fn;
+}
+
+/* Register a hits function to be called to show hits to the user at the
+ * right of the prompt. */
+void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
+    hintsCallback = fn;
+}
+
+/* Register a function to free the hints returned by the hints callback
+ * registered with linenoiseSetHintsCallback(). */
+void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
+    freeHintsCallback = fn;
+}
+
+/* This function is used by the callback function registered by the user
+ * in order to add completion options given the input string when the
+ * user typed <tab>. See the example.c source code for a very easy to
+ * understand example. */
+void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
+    size_t len = strlen(str);
+    char *copy, **cvec;
+
+    copy = malloc(len+1);
+    if (copy == NULL) return;
+    memcpy(copy,str,len+1);
+    cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
+    if (cvec == NULL) {
+        free(copy);
+        return;
+    }
+    lc->cvec = cvec;
+    lc->cvec[lc->len++] = copy;
+}
+
+/* =========================== Line editing ================================= */
+
+/* We define a very simple "append buffer" structure, that is an heap
+ * allocated string where we can append to. This is useful in order to
+ * write all the escape sequences in a buffer and flush them to the standard
+ * output in a single call, to avoid flickering effects. */
+struct abuf {
+    char *b;
+    int len;
+};
+
+static void abInit(struct abuf *ab) {
+    ab->b = NULL;
+    ab->len = 0;
+}
+
+static void abAppend(struct abuf *ab, const char *s, int len) {
+    char *new = realloc(ab->b,ab->len+len);
+
+    if (new == NULL) return;
+    memcpy(new+ab->len,s,len);
+    ab->b = new;
+    ab->len += len;
+}
+
+static void abFree(struct abuf *ab) {
+    free(ab->b);
+}
+
+/* Helper of refreshSingleLine() and refreshMultiLine() to show hints
+ * to the right of the prompt. */
+void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
+    char seq[64];
+    if (hintsCallback && plen+l->len < l->cols) {
+        int color = -1, bold = 0;
+        char *hint = hintsCallback(l->buf,&color,&bold);
+        if (hint) {
+            int hintlen = strlen(hint);
+            int hintmaxlen = l->cols-(plen+l->len);
+            if (hintlen > hintmaxlen) hintlen = hintmaxlen;
+            if (bold == 1 && color == -1) color = 37;
+            if (color != -1 || bold != 0)
+                snprintf(seq,64,"\033[%d;%d;49m",bold,color);
+            abAppend(ab,seq,strlen(seq));
+            abAppend(ab,hint,hintlen);
+            if (color != -1 || bold != 0)
+                abAppend(ab,"\033[0m",4);
+            /* Call the function to free the hint returned. */
+            if (freeHintsCallback) freeHintsCallback(hint);
+        }
+    }
+}
+
+/* Single line low level line refresh.
+ *
+ * Rewrite the currently edited line accordingly to the buffer content,
+ * cursor position, and number of columns of the terminal. */
+static void refreshSingleLine(struct linenoiseState *l) {
+    char seq[64];
+    size_t plen = l->plen;
+    char *buf = l->buf;
+    size_t len = l->len;
+    size_t pos = l->pos;
+    struct abuf ab;
+
+    while((plen+pos) >= l->cols) {
+        buf++;
+        len--;
+        pos--;
+    }
+    while (plen+len > l->cols) {
+        len--;
+    }
+
+    abInit(&ab);
+    /* Cursor to left edge */
+    snprintf(seq,64,"\r");
+    abAppend(&ab,seq,strlen(seq));
+    /* Write the prompt and the current buffer content */
+    abAppend(&ab,l->prompt,strlen(l->prompt));
+    abAppend(&ab,buf,len);
+    /* Show hits if any. */
+    refreshShowHints(&ab,l,plen);
+    /* Erase to right */
+    snprintf(seq,64,"\x1b[0K");
+    abAppend(&ab,seq,strlen(seq));
+    /* Move cursor to original position. */
+    snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
+    abAppend(&ab,seq,strlen(seq));
+    if (fwrite(ab.b, ab.len, 1, stdout) == -1) {} /* Can't recover from write error. */
+    abFree(&ab);
+}
+
+/* Multi line low level line refresh.
+ *
+ * Rewrite the currently edited line accordingly to the buffer content,
+ * cursor position, and number of columns of the terminal. */
+static void refreshMultiLine(struct linenoiseState *l) {
+    char seq[64];
+    int plen = l->plen;
+    int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
+    int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
+    int rpos2; /* rpos after refresh. */
+    int col; /* colum position, zero-based. */
+    int old_rows = l->maxrows;
+    int j;
+    struct abuf ab;
+
+    /* Update maxrows if needed. */
+    if (rows > (int)l->maxrows) l->maxrows = rows;
+
+    /* First step: clear all the lines used before. To do so start by
+     * going to the last row. */
+    abInit(&ab);
+    if (old_rows-rpos > 0) {
+        lndebug("go down %d", old_rows-rpos);
+        snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
+        abAppend(&ab,seq,strlen(seq));
+    }
+
+    /* Now for every row clear it, go up. */
+    for (j = 0; j < old_rows-1; j++) {
+        lndebug("clear+up");
+        snprintf(seq,64,"\r\x1b[0K\x1b[1A");
+        abAppend(&ab,seq,strlen(seq));
+    }
+
+    /* Clean the top line. */
+    lndebug("clear");
+    snprintf(seq,64,"\r\x1b[0K");
+    abAppend(&ab,seq,strlen(seq));
+
+    /* Write the prompt and the current buffer content */
+    abAppend(&ab,l->prompt,strlen(l->prompt));
+    abAppend(&ab,l->buf,l->len);
+
+    /* Show hits if any. */
+    refreshShowHints(&ab,l,plen);
+
+    /* If we are at the very end of the screen with our prompt, we need to
+     * emit a newline and move the prompt to the first column. */
+    if (l->pos &&
+        l->pos == l->len &&
+        (l->pos+plen) % l->cols == 0)
+    {
+        lndebug("<newline>");
+        abAppend(&ab,"\n",1);
+        snprintf(seq,64,"\r");
+        abAppend(&ab,seq,strlen(seq));
+        rows++;
+        if (rows > (int)l->maxrows) l->maxrows = rows;
+    }
+
+    /* Move cursor to right position. */
+    rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
+    lndebug("rpos2 %d", rpos2);
+
+    /* Go up till we reach the expected positon. */
+    if (rows-rpos2 > 0) {
+        lndebug("go-up %d", rows-rpos2);
+        snprintf(seq,64,"\x1b[%dA", rows-rpos2);
+        abAppend(&ab,seq,strlen(seq));
+    }
+
+    /* Set column. */
+    col = (plen+(int)l->pos) % (int)l->cols;
+    lndebug("set col %d", 1+col);
+    if (col)
+        snprintf(seq,64,"\r\x1b[%dC", col);
+    else
+        snprintf(seq,64,"\r");
+    abAppend(&ab,seq,strlen(seq));
+
+    lndebug("\n");
+    l->oldpos = l->pos;
+
+    if (fwrite(ab.b,ab.len,1,stdout) == -1) {} /* Can't recover from write error. */
+    abFree(&ab);
+}
+
+/* Calls the two low level functions refreshSingleLine() or
+ * refreshMultiLine() according to the selected mode. */
+static void refreshLine(struct linenoiseState *l) {
+    if (mlmode)
+        refreshMultiLine(l);
+    else
+        refreshSingleLine(l);
+}
+
+/* Insert the character 'c' at cursor current position.
+ *
+ * On error writing to the terminal -1 is returned, otherwise 0. */
+int linenoiseEditInsert(struct linenoiseState *l, char c) {
+    if (l->len < l->buflen) {
+        if (l->len == l->pos) {
+            l->buf[l->pos] = c;
+            l->pos++;
+            l->len++;
+            l->buf[l->len] = '\0';
+            if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
+                /* Avoid a full update of the line in the
+                 * trivial case. */
+                if (fwrite(&c,1,1,stdout) == -1) return -1;
+            } else {
+                refreshLine(l);
+            }
+        } else {
+            memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
+            l->buf[l->pos] = c;
+            l->len++;
+            l->pos++;
+            l->buf[l->len] = '\0';
+            refreshLine(l);
+        }
+    }
+    return 0;
+}
+
+/* Move cursor on the left. */
+void linenoiseEditMoveLeft(struct linenoiseState *l) {
+    if (l->pos > 0) {
+        l->pos--;
+        refreshLine(l);
+    }
+}
+
+/* Move cursor on the right. */
+void linenoiseEditMoveRight(struct linenoiseState *l) {
+    if (l->pos != l->len) {
+        l->pos++;
+        refreshLine(l);
+    }
+}
+
+/* Move cursor to the start of the line. */
+void linenoiseEditMoveHome(struct linenoiseState *l) {
+    if (l->pos != 0) {
+        l->pos = 0;
+        refreshLine(l);
+    }
+}
+
+/* Move cursor to the end of the line. */
+void linenoiseEditMoveEnd(struct linenoiseState *l) {
+    if (l->pos != l->len) {
+        l->pos = l->len;
+        refreshLine(l);
+    }
+}
+
+/* Substitute the currently edited line with the next or previous history
+ * entry as specified by 'dir'. */
+#define LINENOISE_HISTORY_NEXT 0
+#define LINENOISE_HISTORY_PREV 1
+void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
+    if (history_len > 1) {
+        /* Update the current history entry before to
+         * overwrite it with the next one. */
+        free(history[history_len - 1 - l->history_index]);
+        history[history_len - 1 - l->history_index] = strdup(l->buf);
+        /* Show the new entry */
+        l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
+        if (l->history_index < 0) {
+            l->history_index = 0;
+            return;
+        } else if (l->history_index >= history_len) {
+            l->history_index = history_len-1;
+            return;
+        }
+        strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
+        l->buf[l->buflen-1] = '\0';
+        l->len = l->pos = strlen(l->buf);
+        refreshLine(l);
+    }
+}
+
+/* Delete the character at the right of the cursor without altering the cursor
+ * position. Basically this is what happens with the "Delete" keyboard key. */
+void linenoiseEditDelete(struct linenoiseState *l) {
+    if (l->len > 0 && l->pos < l->len) {
+        memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
+        l->len--;
+        l->buf[l->len] = '\0';
+        refreshLine(l);
+    }
+}
+
+/* Backspace implementation. */
+void linenoiseEditBackspace(struct linenoiseState *l) {
+    if (l->pos > 0 && l->len > 0) {
+        memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
+        l->pos--;
+        l->len--;
+        l->buf[l->len] = '\0';
+        refreshLine(l);
+    }
+}
+
+/* Delete the previosu word, maintaining the cursor at the start of the
+ * current word. */
+void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
+    size_t old_pos = l->pos;
+    size_t diff;
+
+    while (l->pos > 0 && l->buf[l->pos-1] == ' ')
+        l->pos--;
+    while (l->pos > 0 && l->buf[l->pos-1] != ' ')
+        l->pos--;
+    diff = old_pos - l->pos;
+    memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
+    l->len -= diff;
+    refreshLine(l);
+}
+
+/* This function is the core of the line editing capability of linenoise.
+ * It expects 'fd' to be already in "raw mode" so that every key pressed
+ * will be returned ASAP to read().
+ *
+ * The resulting string is put into 'buf' when the user type enter, or
+ * when ctrl+d is typed.
+ *
+ * The function returns the length of the current buffer. */
+static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
+{
+    struct linenoiseState l;
+
+    /* Populate the linenoise state that we pass to functions implementing
+     * specific editing functionalities. */
+    l.buf = buf;
+    l.buflen = buflen;
+    l.prompt = prompt;
+    l.plen = strlen(prompt);
+    l.oldpos = l.pos = 0;
+    l.len = 0;
+    l.cols = getColumns();
+    l.maxrows = 0;
+    l.history_index = 0;
+
+    /* Buffer starts empty. */
+    l.buf[0] = '\0';
+    l.buflen--; /* Make sure there is always space for the nulterm */
+
+    /* The latest history entry is always our current buffer, that
+     * initially is just an empty string. */
+    linenoiseHistoryAdd("");
+
+    int pos1 = getCursorPosition();
+    if (fwrite(prompt,l.plen,1,stdout) == -1) return -1;
+    int pos2 = getCursorPosition();
+    if (pos1 >= 0 && pos2 >= 0) {
+        l.plen = pos2 - pos1;
+    }
+    while(1) {
+        char c;
+        int nread;
+        char seq[3];
+
+        nread = fread(&c, 1, 1, stdin);
+        if (nread <= 0) return l.len;
+
+        /* Only autocomplete when the callback is set. It returns < 0 when
+         * there was an error reading from fd. Otherwise it will return the
+         * character that should be handled next. */
+        if (c == 9 && completionCallback != NULL) {
+            int c2 = completeLine(&l);
+            /* Return on errors */
+            if (c2 < 0) return l.len;
+            /* Read next character when 0 */
+            if (c2 == 0) continue;
+            c = c2;
+        }
+
+        switch(c) {
+        case ENTER:    /* enter */
+            history_len--;
+            free(history[history_len]);
+            if (mlmode) linenoiseEditMoveEnd(&l);
+            if (hintsCallback) {
+                /* Force a refresh without hints to leave the previous
+                 * line as the user typed it after a newline. */
+                linenoiseHintsCallback *hc = hintsCallback;
+                hintsCallback = NULL;
+                refreshLine(&l);
+                hintsCallback = hc;
+            }
+            return (int)l.len;
+        case CTRL_C:     /* ctrl-c */
+            errno = EAGAIN;
+            return -1;
+        case BACKSPACE:   /* backspace */
+        case 8:     /* ctrl-h */
+            linenoiseEditBackspace(&l);
+            break;
+        case CTRL_D:     /* ctrl-d, remove char at right of cursor, or if the
+                            line is empty, act as end-of-file. */
+            if (l.len > 0) {
+                linenoiseEditDelete(&l);
+            } else {
+                history_len--;
+                free(history[history_len]);
+                return -1;
+            }
+            break;
+        case CTRL_T:    /* ctrl-t, swaps current character with previous. */
+            if (l.pos > 0 && l.pos < l.len) {
+                int aux = buf[l.pos-1];
+                buf[l.pos-1] = buf[l.pos];
+                buf[l.pos] = aux;
+                if (l.pos != l.len-1) l.pos++;
+                refreshLine(&l);
+            }
+            break;
+        case CTRL_B:     /* ctrl-b */
+            linenoiseEditMoveLeft(&l);
+            break;
+        case CTRL_F:     /* ctrl-f */
+            linenoiseEditMoveRight(&l);
+            break;
+        case CTRL_P:    /* ctrl-p */
+            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
+            break;
+        case CTRL_N:    /* ctrl-n */
+            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
+            break;
+        case ESC:    /* escape sequence */
+            /* Read the next two bytes representing the escape sequence. */
+            if (fread(seq, 1, 2, stdin) < 2) break;
+
+            /* ESC [ sequences. */
+            if (seq[0] == '[') {
+                if (seq[1] >= '0' && seq[1] <= '9') {
+                    /* Extended escape, read additional byte. */
+                    if (fread(seq+2, 1, 1, stdin) == -1) break;
+                    if (seq[2] == '~') {
+                        switch(seq[1]) {
+                        case '3': /* Delete key. */
+                            linenoiseEditDelete(&l);
+                            break;
+                        }
+                    }
+                } else {
+                    switch(seq[1]) {
+                    case 'A': /* Up */
+                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
+                        break;
+                    case 'B': /* Down */
+                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
+                        break;
+                    case 'C': /* Right */
+                        linenoiseEditMoveRight(&l);
+                        break;
+                    case 'D': /* Left */
+                        linenoiseEditMoveLeft(&l);
+                        break;
+                    case 'H': /* Home */
+                        linenoiseEditMoveHome(&l);
+                        break;
+                    case 'F': /* End*/
+                        linenoiseEditMoveEnd(&l);
+                        break;
+                    }
+                }
+            }
+
+            /* ESC O sequences. */
+            else if (seq[0] == 'O') {
+                switch(seq[1]) {
+                case 'H': /* Home */
+                    linenoiseEditMoveHome(&l);
+                    break;
+                case 'F': /* End*/
+                    linenoiseEditMoveEnd(&l);
+                    break;
+                }
+            }
+            break;
+        default:
+            if (linenoiseEditInsert(&l,c)) return -1;
+            break;
+        case CTRL_U: /* Ctrl+u, delete the whole line. */
+            buf[0] = '\0';
+            l.pos = l.len = 0;
+            refreshLine(&l);
+            break;
+        case CTRL_K: /* Ctrl+k, delete from current to end of line. */
+            buf[l.pos] = '\0';
+            l.len = l.pos;
+            refreshLine(&l);
+            break;
+        case CTRL_A: /* Ctrl+a, go to the start of the line */
+            linenoiseEditMoveHome(&l);
+            break;
+        case CTRL_E: /* ctrl+e, go to the end of the line */
+            linenoiseEditMoveEnd(&l);
+            break;
+        case CTRL_L: /* ctrl+l, clear screen */
+            linenoiseClearScreen();
+            refreshLine(&l);
+            break;
+        case CTRL_W: /* ctrl+w, delete previous word */
+            linenoiseEditDeletePrevWord(&l);
+            break;
+        }
+    }
+    return l.len;
+}
+
+
+static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
+    int count;
+
+    if (buflen == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    count = linenoiseEdit(buf, buflen, prompt);
+    printf("\n");
+    return count;
+}
+
+/* The high level function that is the main API of the linenoise library. */
+char *linenoise(const char *prompt) {
+    char buf[LINENOISE_MAX_LINE];
+    int count;
+
+    count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
+    if (count == -1) return NULL;
+    return strdup(buf);
+}
+
+/* This is just a wrapper the user may want to call in order to make sure
+ * the linenoise returned buffer is freed with the same allocator it was
+ * created with. Useful when the main program is using an alternative
+ * allocator. */
+void linenoiseFree(void *ptr) {
+    free(ptr);
+}
+
+/* ================================ History ================================= */
+
+void linenoiseHistoryFree() {
+    if (history) {
+        for (int j = 0; j < history_len; j++) {
+            free(history[j]);
+        }
+        free(history);
+    }
+    history = NULL;
+}
+
+/* This is the API call to add a new entry in the linenoise history.
+ * It uses a fixed array of char pointers that are shifted (memmoved)
+ * when the history max length is reached in order to remove the older
+ * entry and make room for the new one, so it is not exactly suitable for huge
+ * histories, but will work well for a few hundred of entries.
+ *
+ * Using a circular buffer is smarter, but a bit more complex to handle. */
+int linenoiseHistoryAdd(const char *line) {
+    char *linecopy;
+
+    if (history_max_len == 0) return 0;
+
+    /* Initialization on first call. */
+    if (history == NULL) {
+        history = malloc(sizeof(char*)*history_max_len);
+        if (history == NULL) return 0;
+        memset(history,0,(sizeof(char*)*history_max_len));
+    }
+
+    /* Don't add duplicated lines. */
+    if (history_len && !strcmp(history[history_len-1], line)) return 0;
+
+    /* Add an heap allocated copy of the line in the history.
+     * If we reached the max length, remove the older line. */
+    linecopy = strdup(line);
+    if (!linecopy) return 0;
+    if (history_len == history_max_len) {
+        free(history[0]);
+        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
+        history_len--;
+    }
+    history[history_len] = linecopy;
+    history_len++;
+    return 1;
+}
+
+/* Set the maximum length for the history. This function can be called even
+ * if there is already some history, the function will make sure to retain
+ * just the latest 'len' elements if the new history length value is smaller
+ * than the amount of items already inside the history. */
+int linenoiseHistorySetMaxLen(int len) {
+    char **new;
+
+    if (len < 1) return 0;
+    if (history) {
+        int tocopy = history_len;
+
+        new = malloc(sizeof(char*)*len);
+        if (new == NULL) return 0;
+
+        /* If we can't copy everything, free the elements we'll not use. */
+        if (len < tocopy) {
+            int j;
+
+            for (j = 0; j < tocopy-len; j++) free(history[j]);
+            tocopy = len;
+        }
+        memset(new,0,sizeof(char*)*len);
+        memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
+        free(history);
+        history = new;
+    }
+    history_max_len = len;
+    if (history_len > history_max_len)
+        history_len = history_max_len;
+    return 1;
+}
+
+/* Save the history in the specified file. On success 0 is returned
+ * otherwise -1 is returned. */
+int linenoiseHistorySave(const char *filename) {
+    FILE *fp;
+    int j;
+
+    fp = fopen(filename,"w");
+    if (fp == NULL) return -1;
+    for (j = 0; j < history_len; j++)
+        fprintf(fp,"%s\n",history[j]);
+    fclose(fp);
+    return 0;
+}
+
+/* Load the history from the specified file. If the file does not exist
+ * zero is returned and no operation is performed.
+ *
+ * If the file exists and the operation succeeded 0 is returned, otherwise
+ * on error -1 is returned. */
+int linenoiseHistoryLoad(const char *filename) {
+    FILE *fp = fopen(filename,"r");
+    char buf[LINENOISE_MAX_LINE];
+
+    if (fp == NULL) return -1;
+
+    while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
+        char *p;
+
+        p = strchr(buf,'\r');
+        if (!p) p = strchr(buf,'\n');
+        if (p) *p = '\0';
+        linenoiseHistoryAdd(buf);
+    }
+    fclose(fp);
+    return 0;
+}
diff --git a/components/console/linenoise/linenoise.h b/components/console/linenoise/linenoise.h
new file mode 100644 (file)
index 0000000..31a7d0f
--- /dev/null
@@ -0,0 +1,74 @@
+/* linenoise.h -- VERSION 1.0
+ *
+ * Guerrilla line editing library against the idea that a line editing lib
+ * needs to be 20,000 lines of C code.
+ *
+ * See linenoise.c for more information.
+ *
+ * ------------------------------------------------------------------------
+ *
+ * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
+ * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *  *  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *  *  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __LINENOISE_H
+#define __LINENOISE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct linenoiseCompletions {
+  size_t len;
+  char **cvec;
+} linenoiseCompletions;
+
+typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *);
+typedef char*(linenoiseHintsCallback)(const char *, int *color, int *bold);
+typedef void(linenoiseFreeHintsCallback)(void *);
+void linenoiseSetCompletionCallback(linenoiseCompletionCallback *);
+void linenoiseSetHintsCallback(linenoiseHintsCallback *);
+void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *);
+void linenoiseAddCompletion(linenoiseCompletions *, const char *);
+
+char *linenoise(const char *prompt);
+void linenoiseFree(void *ptr);
+int linenoiseHistoryAdd(const char *line);
+int linenoiseHistorySetMaxLen(int len);
+int linenoiseHistorySave(const char *filename);
+int linenoiseHistoryLoad(const char *filename);
+void linenoiseHistoryFree();
+void linenoiseClearScreen(void);
+void linenoiseSetMultiLine(int ml);
+void linenoisePrintKeyCodes(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __LINENOISE_H */
diff --git a/components/console/split_argv.c b/components/console/split_argv.c
new file mode 100644 (file)
index 0000000..79ae918
--- /dev/null
@@ -0,0 +1,120 @@
+// Copyright 2016-2017 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+
+#define SS_FLAG_ESCAPE 0x8
+
+typedef enum {
+    /* parsing the space between arguments */
+    SS_SPACE = 0x0,
+    /* parsing an argument which isn't quoted */
+    SS_ARG = 0x1,
+    /* parsing a quoted argument */
+    SS_QUOTED_ARG = 0x2,
+    /* parsing an escape sequence within unquoted argument */
+    SS_ARG_ESCAPED = SS_ARG | SS_FLAG_ESCAPE,
+    /* parsing an escape sequence within a quoted argument */
+    SS_QUOTED_ARG_ESCAPED = SS_QUOTED_ARG | SS_FLAG_ESCAPE,
+} split_state_t;
+
+size_t esp_console_split_argv(char *line, char **argv, size_t argv_size)
+{
+    const int QUOTE = '"';
+    const int ESCAPE = '\\';
+    const int SPACE = ' ';
+    split_state_t state = SS_SPACE;
+    int argc = 0;
+    char *next_arg_start = line;
+    char *out_ptr = line;
+    for (char *in_ptr = line; argc < argv_size - 1; ++in_ptr) {
+        int char_in = (unsigned char) *in_ptr;
+        if (char_in == 0) {
+            break;
+        }
+        int char_out = -1;
+
+        /* helper function, called when done with an argument */
+        void end_arg() {
+            char_out = 0;
+            argv[argc++] = next_arg_start;
+            state = SS_SPACE;
+        }
+
+        switch (state) {
+        case SS_SPACE:
+            if (char_in == SPACE) {
+                /* skip space */
+            } else if (char_in == QUOTE) {
+                next_arg_start = out_ptr;
+                state = SS_QUOTED_ARG;
+            } else if (char_in == ESCAPE) {
+                next_arg_start = out_ptr;
+                state = SS_ARG_ESCAPED;
+            } else {
+                next_arg_start = out_ptr;
+                state = SS_ARG;
+                char_out = char_in;
+            }
+            break;
+
+        case SS_QUOTED_ARG:
+            if (char_in == QUOTE) {
+                end_arg();
+            } else if (char_in == ESCAPE) {
+                state = SS_QUOTED_ARG_ESCAPED;
+            } else {
+                char_out = char_in;
+            }
+            break;
+
+        case SS_ARG_ESCAPED:
+        case SS_QUOTED_ARG_ESCAPED:
+            if (char_in == ESCAPE || char_in == QUOTE || char_in == SPACE) {
+                char_out = char_in;
+            } else {
+                /* unrecognized escape character, skip */
+            }
+            state = (split_state_t) (state & (~SS_FLAG_ESCAPE));
+            break;
+
+        case SS_ARG:
+            if (char_in == SPACE) {
+                end_arg();
+            } else if (char_in == ESCAPE) {
+                state = SS_ARG_ESCAPED;
+            } else {
+                char_out = char_in;
+            }
+            break;
+        }
+        /* need to output anything? */
+        if (char_out >= 0) {
+            *out_ptr = char_out;
+            ++out_ptr;
+        }
+    }
+    /* make sure the final argument is terminated */
+    *out_ptr = 0;
+    /* finalize the last argument */
+    if (state != SS_SPACE && argc < argv_size - 1) {
+        argv[argc++] = next_arg_start;
+    }
+    /* add a NULL at the end of argv */
+    argv[argc] = NULL;
+
+    return argc;
+}
index 11e11b52862a111dbbdb36b7f1115cf05e2ef1cc..81732ba49c9df47088f69260c6405fc47e591df9 100644 (file)
@@ -28,6 +28,10 @@ Additional third party copyrighted code is included under the following licenses
 
 * `JSMN`_ JSON Parser (components/jsmn) Copyright (c) 2010 Serge A. Zaitsev and licensed under the MIT license.
 
+* `argtable3`_ arugment parsing library Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann and licensed under 3-clause BSD license.
+
+* `linenoise`_ line editing library Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>, Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>, licensed under 2-clause BSD license.
+
 Where source code headers specify Copyright & License information, this information takes precedence over the summaries made here.
 
 ROM Source Code Copyrights
@@ -106,3 +110,6 @@ Copyright (C) 2011, ChaN, all right reserved.
 .. _FreeBSD net80211: https://github.com/freebsd/freebsd/tree/master/sys/net80211
 .. _TJpgDec: http://elm-chan.org/fsw/tjpgd/00index.html
 .. _JSMN: http://zserge.com/jsmn.html
+.. _argtable3: https://github.com/argtable/argtable3
+.. _linenoise: https://github.com/antirez/linenoise
+
diff --git a/docs/api-guides/console.rst b/docs/api-guides/console.rst
new file mode 100644 (file)
index 0000000..490c994
--- /dev/null
@@ -0,0 +1,143 @@
+Console
+=======
+
+ESP-IDF provides ``console`` component, which includes building blocks needed to develop an interactive console over serial port. This component includes following facilities:
+
+- Line editing, provided by `linenoise`_ library. This includes handling of backspace and arrow keys, scrolling through command history, command auto-completion, and argument hints.
+- Splitting of command line into arguments.
+- Argument parsing, provided by `argtable3`_ library. This library includes APIs useful for parsing GNU style command line arguments.
+- Functions for registration and dispatching of commands.
+
+These facilities can be used together or independently. For example, it is possible to use line editing and command registration features, but use ``getopt`` or custom code for argument parsing, instead of `argtable3`_. Likewise, it is possible to use simpler means of command input (such as ``fgets``) together with the rest of the means for command splitting and argument parsing.
+
+Line editing
+------------
+
+Line editing feature lets users compose commands by typing them, erasing symbols using 'backspace' key, navigating within the command using left/right keys, navigating to previously typed commands using up/down keys, and performing autocompletion using 'tab' key. 
+
+.. note:: This feature relies on ANSI escape sequence support in the terminal application. As such, serial monitors which display raw UART data can not be used together with the line editing library. If you see ``[6n`` or similar escape sequence when running get_started/console example instead of a command prompt (``[esp32]>``), it means that the serial monitor does not support escape sequences. Programs which are known to work are  GNU screen, minicom, and idf_monitor.py (which can be invoked using ``make monitor`` from project directory).
+
+Here is an overview of functions provided by `linenoise`_ library.
+
+Configuration
+^^^^^^^^^^^^^
+
+Linenoise library does not need explicit initialization. However, some configuration defaults may need to be changed before invoking the main line editing function.
+
+``linenoiseClearScreen``
+  Clear terminal screen using an escape sequence and position the cursor at the top left corner.
+
+``linenoiseSetMultiLine``
+  Switch between single line and multi line editing modes. In single line mode, if the length of the command exceeds the width of the terminal, the command text is scrolled within the line to show the end of the text. In this case the beginning of the text is hidden. Single line needs less data to be sent to refresh screen on each key press, so exhibits less glitching compared to the multi line mode. On the flip side, editing commands and copying command text from terminal in single line mode is harder. Default is single line mode.
+
+
+Main loop
+^^^^^^^^^
+
+``linenoise``
+  In most cases, console applications have some form of read/eval loop. ``linenoise`` is the single function which handles user's key presses and returns completed line once 'enter' key is pressed. As such, it handles the 'read' part of the loop.
+
+``linenoiseFree``
+  This function must be called to release the command line buffer obtained from ``linenoise`` function.
+
+Hints and completions
+^^^^^^^^^^^^^^^^^^^^^
+
+``linenoiseSetCompletionCallback``
+  When user presses 'tab' key, linenoise library invokes completion callback. The callback should inspect the contents of the command typed so far and provide a list of possible completions using calls to ``linenoiseAddCompletion`` function. ``linenoiseSetCompletionCallback`` function should be called to register this completion callback, if completion feature is desired.
+
+  ``console`` component provides a ready made function to provide completions for registered commands, ``esp_console_get_completion`` (see below).
+
+``linenoiseAddCompletion``
+  Function to be called by completion callback to inform the library about possible completions of the currently typed command.
+
+``linenoiseSetHintsCallback``
+  Whenever user input changes, linenoise invokes hints callback. This callback can inspect the command line typed so far, and provide a string with hints (which can include list of command arguments, for example). The library then displays the hint text on the same line where editing happens, possibly with a different color.
+
+``linenoiseSetFreeHintsCallback``
+  If hint string returned by hints callback is dynamically allocated or needs to be otherwise recycled, the function which performs such cleanup should be registered via ``linenoiseSetFreeHintsCallback``.
+
+
+History
+^^^^^^^
+
+``linenoiseHistorySetMaxLen``
+  This function sets the number of most recently typed commands to be kept in memory. Users can navigate the history using up/down arrows.
+
+``linenoiseHistoryAdd``
+  Linenoise does not automatically add commands to history. Instead, applications need to call this function to add command strings to the history.
+
+``linenoiseHistorySave``
+  Function saves command history from RAM to a text file, for example on an SD card or on a filesystem in flash memory.
+
+``linenoiseHistoryLoad``
+  Counterpart to ``linenoiseHistorySave``, loads history from a file.
+
+``linenoiseHistoryFree``
+  Releases memory used to store command history. Call this function when done working with linenoise library.
+
+Splitting of command line into arguments
+----------------------------------------
+
+``console`` component provides ``esp_console_split_argv`` function to split command line string into arguments. The function returns the number of arguments found (``argc``) and fills an array of pointers which can be passed as ``argv`` argument to any function which accepts arguments in ``argc, argv`` format.
+
+The command line is split into arguments according to the following rules:
+
+- Arguments are separated by spaces
+- If spaces within arguments are required, they can be escaped using ``\`` (backslash) character.
+- Other escape sequences which are recognized are ``\\`` (which produces literal backslash) and ``\"``, which produces a double quote.
+- Arguments can be quoted using double quotes. Quotes may appear only in the beginning and at the end of the argument. Quotes within the argument must be escaped as mentioned above. Quotes surrounding the argument are stripped by ``esp_console_split_argv`` function.
+
+Examples:
+
+- ``abc def 1 20 .3`` ⟶ [ ``abc``, ``def``, ``1``, ``20``, ``.3`` ]
+- ``abc "123 456" def`` ⟶ [ ``abc``, ``123 456``, ``def`` ]
+- ```a\ b\\c\"`` ⟶ [ ``a b\c"`` ]
+
+
+Argument parsing
+----------------
+
+For argument parsing, ``console`` component includes `argtable3`_ library. Please see `tutorial`_ for an introduction to `argtable3`_. Github repository also includes `examples`_.
+
+.. _argtable3: http://www.argtable.org/
+.. _linenoise: https://github.com/antirez/linenoise
+.. _tutorial: http://www.argtable.org/tutorial/
+.. _examples: https://github.com/argtable/argtable3/tree/master/examples
+
+
+Command registration and dispatching
+------------------------------------
+
+``console`` component includes utility functions which handle registration of commands, matching commands typed by the user to registered ones, and calling these commands with the arguments given on the command line.
+
+Application first initializes command registration module using a call to ``esp_console_init``, and calls ``esp_console_cmd_register`` function to register command handlers.
+
+For each command, application provides the following information (in the form of ``esp_console_cmd_t`` structure):
+
+- Command name (string without spaces)
+- Help text explaining what the command does
+- Optional hint text listing the arguments of the command. If application uses Argtable3 for argument parsing, hint text can be generated automatically by providing a pointer to argtable argument definitions structure instead.
+- The command handler function.
+
+A few other functions are provided by the command registration module:
+
+``esp_console_run``
+  This function takes the command line string, splits it into argc/argv argument list using ``esp_console_split_argv``, looks up the command in the list of registered components, and if it is found, executes its handler.
+
+``esp_console_split_argv``
+  Adds ``help`` command to the list of registered commands. This command prints the list of all the registered commands, along with their arguments and help texts.
+
+``esp_console_get_completion``
+  Callback function to be used with ``linenoiseSetCompletionCallback`` from linenoise library. Provides completions to linenoise based on the list of registered commands.
+
+``esp_console_get_hint``
+  Callback function to be used with ``linenoiseSetHintsCallback`` from linenoise library. Provides argument hints for registered commands to linenoise.
+
+Example
+-------
+
+Example application illustrating usage of the ``console`` component is available in ``examples/system/console`` directory. This example shows how to initialize UART and VFS functions, set up linenoise library, read and handle commands from UART, and store command history in Flash. See README.md in the example directory for more details.
+
+
+
index f3e26e016c462504cfa209909df3248bf71e5291..0f155bafb8fadcb38cc6ed77564bb93286a63e25 100644 (file)
@@ -16,5 +16,6 @@ API Guides
    ULP Coprocessor <ulp>
    Unit Testing <unit-tests>
    Application Level Tracing <app_trace>
+   Console Component <console>
    ROM debug console <romconsole>
    WiFi Driver <wifi>
diff --git a/examples/system/console/Makefile b/examples/system/console/Makefile
new file mode 100644 (file)
index 0000000..952298b
--- /dev/null
@@ -0,0 +1,9 @@
+#
+# This is a project Makefile. It is assumed the directory this Makefile resides in is a
+# project subdirectory.
+#
+
+PROJECT_NAME := console
+
+include $(IDF_PATH)/make/project.mk
+
diff --git a/examples/system/console/README.md b/examples/system/console/README.md
new file mode 100644 (file)
index 0000000..9341a5c
--- /dev/null
@@ -0,0 +1,108 @@
+# Console example
+
+This example illustrates usage of `console` component to create an interactive shell.
+
+## Configuring UART and VFS
+
+``initialize_console`` function configures some aspects of UART and VFS relevant to the operation of console:
+
+- By default `stdin` and `stdout` are buffered streams. This means that the text written to `stdout` will not be immediately sent to UART. This is not the desirable behavior for the console, so buffering for `stdin` and `stdout` is disabled using `setvbuf` function.
+
+- Line endings are configured to match those expected/generated by common serial monitor programs, such as `screen`, `minicom`, and the `idf_monitor.py` included in the SDK. The default behavior for these commands is:
+    - When 'enter' key is pressed on the keyboard, `CR` (0x13) code is sent to the serial device.
+    - To move the cursor to the beginning of the next line, serial device needs to send `CR LF` (0x13 0x10) sequence.
+
+- UART driver is initialized, and VFS is configured to use UART driver's interrupt-driver read and write functions.
+
+## Line editing
+
+The main source file of the example illustrates how to use `linenoise` library, including line completion, hints, and history.
+
+## Commands
+
+Several commands are registered using `esp_console_cmd_register` function. See `register_wifi` and `register_system` functions in `cmd_wifi.c` and `cmd_system.c` files.
+
+## Command handling
+
+Main loop inside `app_main` function illustrates how to use `linenoise` and `esp_console_run` to implement read/eval loop.
+
+## Argument parsing
+
+Several commands implemented in `cmd_wifi.c` and `cmd_system.c` use Argtable3 library to parse and check the arguments.
+
+## Command history
+
+Each time a new command line is obtained from `linenoise`, it is written into history and the history is saved into a file in flash memory. On reset, history is initialized from that file.
+
+# Example output
+
+Here is an sample session with the console example. GPIO15 is connected to GND to remove boot log output.
+
+```
+This is an example of ESP-IDF console component.
+Type 'help' to get the list of commands.
+Use UP/DOWN arrows to navigate through command history.
+Press TAB when typing command name to auto-complete.
+[esp32]> help
+help 
+  Print the list of registered commands
+
+free 
+  Get the total size of heap memory available
+
+restart 
+  Restart the program
+
+deep_sleep  [-t <t>] [--io=<n>] [--io_level=<0|1>]
+  Enter deep sleep mode. Two wakeup modes are supported: timer and GPIO. If no
+  wakeup option is specified, will sleep indefinitely.
+  -t, --time=<t>  Wake up time, ms
+      --io=<n>  If specified, wakeup using GPIO with given number
+  --io_level=<0|1>  GPIO level to trigger wakeup
+
+join  [--timeout=<t>] <ssid> [<pass>]
+  Join WiFi AP as a station
+  --timeout=<t>  Connection timeout, ms
+        <ssid>  SSID of AP
+        <pass>  PSK of AP
+
+[esp32]> free
+257200
+[esp32]> deep_sleep -t 1000
+I (146929) deep_sleep: Enabling timer wakeup, timeout=1000000us
+I (619) heap_init: Initializing. RAM available for dynamic allocation:
+I (620) heap_init: At 3FFAE2A0 len 00001D60 (7 KiB): DRAM
+I (626) heap_init: At 3FFB7EA0 len 00028160 (160 KiB): DRAM
+I (645) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM
+I (664) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
+I (684) heap_init: At 40093EA8 len 0000C158 (48 KiB): IRAM
+
+This is an example of ESP-IDF console component.
+Type 'help' to get the list of commands.
+Use UP/DOWN arrows to navigate through command history.
+Press TAB when typing command name to auto-complete.
+[esp32]> join --timeout 10000 test_ap test_password
+I (182639) connect: Connecting to 'test_ap'
+I (184619) connect: Connected
+[esp32]> free
+212328
+[esp32]> restart
+I (205639) restart: Restarting
+I (616) heap_init: Initializing. RAM available for dynamic allocation:
+I (617) heap_init: At 3FFAE2A0 len 00001D60 (7 KiB): DRAM
+I (623) heap_init: At 3FFB7EA0 len 00028160 (160 KiB): DRAM
+I (642) heap_init: At 3FFE0440 len 00003BC0 (14 KiB): D/IRAM
+I (661) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
+I (681) heap_init: At 40093EA8 len 0000C158 (48 KiB): IRAM
+
+This is an example of ESP-IDF console component.
+Type 'help' to get the list of commands.
+Use UP/DOWN arrows to navigate through command history.
+Press TAB when typing command name to auto-complete.
+[esp32]> 
+
+```
+
+---
+
+See the README.md file in the upper level 'examples' directory for more information about examples.
diff --git a/examples/system/console/main/Kconfig.projbuild b/examples/system/console/main/Kconfig.projbuild
new file mode 100644 (file)
index 0000000..e80c1c6
--- /dev/null
@@ -0,0 +1,11 @@
+menu "Example Configuration"
+
+config STORE_HISTORY
+    bool "Store command history in flash"
+    default y
+    help
+        Linenoise line editing library provides functions to save and load
+        command history. If this option is enabled, initalizes a FAT filesystem
+        and uses it to store command history.
+
+endmenu
\ No newline at end of file
diff --git a/examples/system/console/main/cmd_decl.h b/examples/system/console/main/cmd_decl.h
new file mode 100644 (file)
index 0000000..969d57d
--- /dev/null
@@ -0,0 +1,15 @@
+/* Console example — declarations of command registration functions.
+
+   This example code is in the Public Domain (or CC0 licensed, at your option.)
+
+   Unless required by applicable law or agreed to in writing, this
+   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+   CONDITIONS OF ANY KIND, either express or implied.
+*/
+#pragma once
+
+// Register system functions
+void register_system();
+
+// Register WiFi functions
+void register_wifi();
diff --git a/examples/system/console/main/cmd_system.c b/examples/system/console/main/cmd_system.c
new file mode 100644 (file)
index 0000000..7faab0b
--- /dev/null
@@ -0,0 +1,246 @@
+/* Console example — various system commands
+
+   This example code is in the Public Domain (or CC0 licensed, at your option.)
+
+   Unless required by applicable law or agreed to in writing, this
+   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+   CONDITIONS OF ANY KIND, either express or implied.
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include "esp_log.h"
+#include "esp_console.h"
+#include "esp_system.h"
+#include "driver/rtc_io.h"
+#include "argtable3/argtable3.h"
+#include "cmd_decl.h"
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "soc/rtc_cntl_reg.h"
+
+static void register_free();
+static void register_restart();
+static void register_deep_sleep();
+static void register_make();
+
+void register_system()
+{
+    register_free();
+    register_restart();
+    register_deep_sleep();
+    register_make();
+}
+
+/** 'restart' command restarts the program */
+
+static int restart(int argc, char** argv)
+{
+    ESP_LOGI(__func__, "Restarting");
+    esp_restart();
+}
+
+static void register_restart()
+{
+    const esp_console_cmd_t cmd = {
+        .command = "restart",
+        .help = "Restart the program",
+        .hint = NULL,
+        .func = &restart,
+    };
+    ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
+}
+
+/** 'free' command prints available heap memory */
+
+static int free_mem(int argc, char** argv)
+{
+    printf("%d\n", esp_get_free_heap_size());
+    return 0;
+}
+
+static void register_free()
+{
+    const esp_console_cmd_t cmd = {
+        .command = "free",
+        .help = "Get the total size of heap memory available",
+        .hint = NULL,
+        .func = &free_mem,
+    };
+    ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
+}
+
+/** 'deep_sleep' command puts the chip into deep sleep mode */
+
+static struct {
+    struct arg_int *wakeup_time;
+    struct arg_int *wakeup_gpio_num;
+    struct arg_int *wakeup_gpio_level;
+    struct arg_end *end;
+} deep_sleep_args;
+
+
+static int deep_sleep(int argc, char** argv)
+{
+    int nerrors = arg_parse(argc, argv, (void**) &deep_sleep_args);
+    if (nerrors != 0) {
+        arg_print_errors(stderr, deep_sleep_args.end, argv[0]);
+        return 1;
+    }
+    if (deep_sleep_args.wakeup_time->count) {
+        uint64_t timeout = 1000ULL * deep_sleep_args.wakeup_time->ival[0];
+        ESP_LOGI(__func__, "Enabling timer wakeup, timeout=%lluus", timeout);
+        ESP_ERROR_CHECK( esp_deep_sleep_enable_timer_wakeup(timeout) );
+    }
+    if (deep_sleep_args.wakeup_gpio_num->count) {
+        int io_num = deep_sleep_args.wakeup_gpio_num->ival[0];
+        if (!rtc_gpio_is_valid_gpio(io_num)) {
+            ESP_LOGE(__func__, "GPIO %d is not an RTC IO", io_num);
+            return 1;
+        }
+        int level = 0;
+        if (deep_sleep_args.wakeup_gpio_level->count) {
+            level = deep_sleep_args.wakeup_gpio_level->ival[0];
+            if (level != 0 && level != 1) {
+                ESP_LOGE(__func__, "Invalid wakeup level: %d", level);
+                return 1;
+            }
+        }
+        ESP_LOGI(__func__, "Enabling wakeup on GPIO%d, wakeup on %s level",
+                io_num, level ? "HIGH" : "LOW");
+
+        ESP_ERROR_CHECK( esp_deep_sleep_enable_ext1_wakeup(1ULL << io_num, level) );
+    }
+    esp_deep_sleep_start();
+}
+
+static void register_deep_sleep()
+{
+    deep_sleep_args.wakeup_time =
+            arg_int0("t", "time", "<t>", "Wake up time, ms");
+    deep_sleep_args.wakeup_gpio_num =
+            arg_int0(NULL, "io", "<n>",
+                     "If specified, wakeup using GPIO with given number");
+    deep_sleep_args.wakeup_gpio_level =
+            arg_int0(NULL, "io_level", "<0|1>", "GPIO level to trigger wakeup");
+    deep_sleep_args.end = arg_end(3);
+
+    const esp_console_cmd_t cmd = {
+        .command = "deep_sleep",
+        .help = "Enter deep sleep mode. "
+                "Two wakeup modes are supported: timer and GPIO. "
+                "If no wakeup option is specified, will sleep indefinitely.",
+        .hint = NULL,
+        .func = &deep_sleep,
+        .argtable = &deep_sleep_args
+    };
+    ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
+}
+
+/** This command helps maintain sanity when testing console example from a console */
+
+static int make(int argc, char** argv)
+{
+    int count = REG_READ(RTC_CNTL_STORE0_REG);
+    if (++count >= 3) {
+        printf("This is not the console you are looking for.\n");
+        return 0;
+    }
+    REG_WRITE(RTC_CNTL_STORE0_REG, count);
+
+    const char* make_output =
+R"(LD build/console.elf
+esptool.py v2.1-beta1
+)";
+
+    const char* flash_output[] = {
+R"(Flashing binaries to serial port )" CONFIG_ESPTOOLPY_PORT R"( (app at offset 0x10000)...
+esptool.py v2.1-beta1
+Connecting....
+)",
+R"(Chip is ESP32D0WDQ6 (revision 0)
+Uploading stub...
+Running stub...
+Stub running...
+Changing baud rate to 921600
+Changed.
+Configuring flash size...
+Auto-detected Flash size: 4MB
+Flash params set to 0x0220
+Compressed 15712 bytes to 9345...
+)",
+R"(Wrote 15712 bytes (9345 compressed) at 0x00001000 in 0.1 seconds (effective 1126.9 kbit/s)...
+Hash of data verified.
+Compressed 333776 bytes to 197830...
+)",
+R"(Wrote 333776 bytes (197830 compressed) at 0x00010000 in 3.3 seconds (effective 810.3 kbit/s)...
+Hash of data verified.
+Compressed 3072 bytes to 82...
+)",
+R"(Wrote 3072 bytes (82 compressed) at 0x00008000 in 0.0 seconds (effective 1588.4 kbit/s)...
+Hash of data verified.
+Leaving...
+Hard resetting...
+)"
+    };
+
+    const char* monitor_output =
+R"(MONITOR
+)" LOG_COLOR_W R"(--- idf_monitor on )" CONFIG_ESPTOOLPY_PORT R"( 115200 ---
+--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H --
+)" LOG_RESET_COLOR;
+
+    bool need_make = false;
+    bool need_flash = false;
+    bool need_monitor = false;
+    for (int i = 1; i < argc; ++i) {
+        if (strcmp(argv[i], "all") == 0) {
+            need_make = true;
+        } else if (strcmp(argv[i], "flash") == 0) {
+            need_make = true;
+            need_flash = true;
+        } else if (strcmp(argv[i], "monitor") == 0) {
+            need_monitor = true;
+        } else if (argv[i][0] == '-') {
+            /* probably -j option */
+        } else if (isdigit((int) argv[i][0])) {
+            /* might be an argument to -j */
+        } else {
+            printf("make: *** No rule to make target `%s'.  Stop.\n", argv[i]);
+            /* Technically this is an error, but let's not spoil the output */
+            return 0;
+        }
+    }
+    if (argc == 1) {
+        need_make = true;
+    }
+    if (need_make) {
+        printf("%s", make_output);
+    }
+    if (need_flash) {
+        size_t n_items = sizeof(flash_output) / sizeof(flash_output[0]);
+        for (int i = 0; i < n_items; ++i) {
+            printf("%s", flash_output[i]);
+            vTaskDelay(200/portTICK_PERIOD_MS);
+        }
+    }
+    if (need_monitor) {
+        printf("%s", monitor_output);
+        esp_restart();
+    }
+    return 0;
+}
+
+static void register_make()
+{
+    const esp_console_cmd_t cmd = {
+        .command = "make",
+        .help = NULL, /* hide from 'help' output */
+        .hint = "all | flash | monitor",
+        .func = &make,
+    };
+    ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
+}
+
+
diff --git a/examples/system/console/main/cmd_wifi.c b/examples/system/console/main/cmd_wifi.c
new file mode 100644 (file)
index 0000000..f0da322
--- /dev/null
@@ -0,0 +1,123 @@
+/* Console example — WiFi commands
+
+   This example code is in the Public Domain (or CC0 licensed, at your option.)
+
+   Unless required by applicable law or agreed to in writing, this
+   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+   CONDITIONS OF ANY KIND, either express or implied.
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include "esp_log.h"
+#include "esp_console.h"
+#include "argtable3/argtable3.h"
+#include "cmd_decl.h"
+#include "freertos/FreeRTOS.h"
+#include "freertos/event_groups.h"
+#include "esp_wifi.h"
+#include "tcpip_adapter.h"
+#include "esp_event_loop.h"
+
+static EventGroupHandle_t wifi_event_group;
+const int CONNECTED_BIT = BIT0;
+
+static esp_err_t event_handler(void *ctx, system_event_t *event)
+{
+    switch(event->event_id) {
+    case SYSTEM_EVENT_STA_GOT_IP:
+        xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
+        break;
+    case SYSTEM_EVENT_STA_DISCONNECTED:
+        esp_wifi_connect();
+        xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
+        break;
+    default:
+        break;
+    }
+    return ESP_OK;
+}
+
+static void initialise_wifi(void)
+{
+    esp_log_level_set("wifi", ESP_LOG_WARN);
+    static bool initialized = false;
+    if (initialized) {
+        return;
+    }
+    tcpip_adapter_init();
+    wifi_event_group = xEventGroupCreate();
+    ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
+    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
+    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
+    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
+    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_NULL) );
+    ESP_ERROR_CHECK( esp_wifi_start() );
+    initialized = true;
+}
+
+static bool wifi_join(const char* ssid, const char* pass, int timeout_ms)
+{
+    initialise_wifi();
+    wifi_config_t wifi_config = { 0 };
+    strncpy((char*) wifi_config.sta.ssid, ssid, sizeof(wifi_config.sta.ssid));
+    if (pass) {
+        strncpy((char*) wifi_config.sta.password, pass, sizeof(wifi_config.sta.password));
+    }
+
+    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
+    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
+    ESP_ERROR_CHECK( esp_wifi_connect() );
+
+    int bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
+            1, 1, timeout_ms / portTICK_PERIOD_MS);
+    return (bits & CONNECTED_BIT) != 0;
+}
+
+/** Arguments used by 'join' function */
+static struct {
+    struct arg_int *timeout;
+    struct arg_str *ssid;
+    struct arg_str *password;
+    struct arg_end *end;
+} join_args;
+
+static int connect(int argc, char** argv)
+{
+    int nerrors = arg_parse(argc, argv, (void**) &join_args);
+    if (nerrors != 0) {
+        arg_print_errors(stderr, join_args.end, argv[0]);
+        return 1;
+    }
+    ESP_LOGI(__func__, "Connecting to '%s'",
+            join_args.ssid->sval[0]);
+
+    bool connected = wifi_join(join_args.ssid->sval[0],
+                           join_args.password->sval[0],
+                           join_args.timeout->ival[0]);
+    if (!connected) {
+        ESP_LOGW(__func__, "Connection timed out");
+        return 1;
+    }
+    ESP_LOGI(__func__, "Connected");
+    return 0;
+}
+
+void register_wifi()
+{
+    join_args.timeout = arg_int0(NULL, "timeout", "<t>", "Connection timeout, ms");
+    join_args.timeout->ival[0] = 5000; // set default value
+    join_args.ssid = arg_str1(NULL, NULL, "<ssid>", "SSID of AP");
+    join_args.password = arg_str0(NULL, NULL, "<pass>", "PSK of AP");
+    join_args.end = arg_end(2);
+
+    const esp_console_cmd_t join_cmd = {
+        .command = "join",
+        .help = "Join WiFi AP as a station",
+        .hint = NULL,
+        .func = &connect,
+        .argtable = &join_args
+    };
+
+    ESP_ERROR_CHECK( esp_console_cmd_register(&join_cmd) );
+}
diff --git a/examples/system/console/main/component.mk b/examples/system/console/main/component.mk
new file mode 100644 (file)
index 0000000..0b9d758
--- /dev/null
@@ -0,0 +1,5 @@
+#
+# "main" pseudo-component makefile.
+#
+# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
+
diff --git a/examples/system/console/main/console_example_main.c b/examples/system/console/main/console_example_main.c
new file mode 100644 (file)
index 0000000..90ccdcb
--- /dev/null
@@ -0,0 +1,147 @@
+/* Console example
+
+   This example code is in the Public Domain (or CC0 licensed, at your option.)
+
+   Unless required by applicable law or agreed to in writing, this
+   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+   CONDITIONS OF ANY KIND, either express or implied.
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include "esp_system.h"
+#include "esp_log.h"
+#include "esp_console.h"
+#include "esp_vfs_dev.h"
+#include "driver/uart.h"
+#include "linenoise/linenoise.h"
+#include "argtable3/argtable3.h"
+#include "cmd_decl.h"
+#include "esp_vfs_fat.h"
+
+static const char* TAG = "example";
+
+/* Console command history can be stored to and loaded from a file.
+ * The easiest way to do this is to use FATFS filesystem on top of
+ * wear_levelling library.
+ */
+#if CONFIG_STORE_HISTORY
+
+#define MOUNT_PATH "/data"
+#define HISTORY_PATH MOUNT_PATH "/history.txt"
+
+static void initialize_filesystem()
+{
+    static wl_handle_t wl_handle;
+    const esp_vfs_fat_mount_config_t mount_config = {
+            .max_files = 4,
+            .format_if_mount_failed = true
+    };
+    esp_err_t err = esp_vfs_fat_spiflash_mount(MOUNT_PATH, "storage", &mount_config, &wl_handle);
+    if (err != ESP_OK) {
+        ESP_LOGE(TAG, "Failed to mount FATFS (0x%x)", err);
+        return;
+    }
+}
+#endif // CONFIG_STORE_HISTORY
+
+static void initialize_console()
+{
+    /* Disable buffering on stdin and stdout */
+    setvbuf(stdin, NULL, _IONBF, 0);
+    setvbuf(stdout, NULL, _IONBF, 0);
+
+    /* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
+    esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
+    /* Move the caret to the beginning of the next line on '\n' */
+    esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
+
+    /* Install UART driver for interrupt-driven reads and writes */
+    ESP_ERROR_CHECK( uart_driver_install(CONFIG_CONSOLE_UART_NUM,
+            256, 0, 0, NULL, 0) );
+
+    /* Tell VFS to use UART driver */
+    esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
+
+    /* Initialize the console */
+    esp_console_config_t console_config = {
+            .max_cmdline_args = 8,
+            .max_cmdline_length = 256,
+#if CONFIG_LOG_COLORS
+            .hint_color = atoi(LOG_COLOR_CYAN)
+#endif
+    };
+    ESP_ERROR_CHECK( esp_console_init(&console_config) );
+
+    /* Configure linenoise line completion library */
+    /* Enable multiline editing. If not set, long commands will scroll within
+     * single line.
+     */
+    linenoiseSetMultiLine(1);
+
+    /* Tell linenoise where to get command completions and hints */
+    linenoiseSetCompletionCallback(&esp_console_get_completion);
+    linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
+
+    /* Set command history size */
+    linenoiseHistorySetMaxLen(100);
+
+#if CONFIG_STORE_HISTORY
+    /* Load command history from filesystem */
+    linenoiseHistoryLoad(HISTORY_PATH);
+#endif
+}
+
+void app_main()
+{
+#if CONFIG_STORE_HISTORY
+    initialize_filesystem();
+#endif
+
+    initialize_console();
+
+    /* Register commands */
+    esp_console_register_help_command();
+    register_system();
+    register_wifi();
+
+    printf("\n"
+           "This is an example of ESP-IDF console component.\n"
+           "Type 'help' to get the list of commands.\n"
+           "Use UP/DOWN arrows to navigate through command history.\n"
+           "Press TAB when typing command name to auto-complete.\n");
+
+    /* Prompt to be printed before each line.
+     * This can be customized, made dynamic, etc.
+     */
+    const char* prompt = LOG_COLOR_I "[esp32]> " LOG_RESET_COLOR;
+
+    /* Main loop */
+    char *line;
+    /* Get a line using linenoise.
+     * The line is returned when ENTER is pressed.
+     */
+    while((line = linenoise(prompt)) != NULL) {
+        if (strlen(line) > 0) {  /* Ignore empty lines */
+            /* Add the command to the history */
+            linenoiseHistoryAdd(line);
+#if CONFIG_STORE_HISTORY
+            /* Save command history to filesystem */
+            linenoiseHistorySave(HISTORY_PATH);
+#endif
+
+            /* Try to run the command */
+            int ret;
+            esp_err_t err = esp_console_run(line, &ret);
+            if (err == ESP_ERR_NOT_FOUND) {
+                printf("Unrecognized command\n");
+            } else if (err == ESP_OK && ret != ESP_OK) {
+                printf("Command returned non-zero error code: 0x%x\n", ret);
+            } else if (err != ESP_OK) {
+                printf("Internal error: 0x%x\n", err);
+            }
+        }
+        /* linenoise allocates line buffer on the heap, so need to free it */
+        linenoiseFree(line);
+    }
+}
diff --git a/examples/system/console/partitions_example.csv b/examples/system/console/partitions_example.csv
new file mode 100644 (file)
index 0000000..7e28b56
--- /dev/null
@@ -0,0 +1,6 @@
+# Name,   Type, SubType, Offset,  Size, Flags
+# Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild
+nvs,      data, nvs,     0x9000,  0x6000,
+phy_init, data, phy,     0xf000,  0x1000,
+factory,  app,  factory, 0x10000, 1M,
+storage,  data, fat,     ,        1M, 
diff --git a/examples/system/console/sdkconfig.defaults b/examples/system/console/sdkconfig.defaults
new file mode 100644 (file)
index 0000000..96cda3d
--- /dev/null
@@ -0,0 +1,13 @@
+# Reduce bootloader log verbosity
+CONFIG_LOG_BOOTLOADER_LEVEL_WARN=y
+CONFIG_LOG_BOOTLOADER_LEVEL=2
+
+# Increase main task stack size
+CONFIG_MAIN_TASK_STACK_SIZE=6144
+
+# Enable filesystem
+CONFIG_PARTITION_TABLE_CUSTOM=y
+CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_example.csv"
+CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET=0x10000
+CONFIG_PARTITION_TABLE_FILENAME="partitions_example.csv"
+CONFIG_APP_OFFSET=0x10000