shithub: sox

Download patch

ref: 8bffa5921fbd71edd9b226a88a6e9e59362a05c1
parent: 4933b58e02567cfd5842c6e7f44308ee01d466ea
parent: 02ebdd61638a3e3afc0c29c9c265166a0d69448f
author: Rob Sykes <robs@users.sourceforge.net>
date: Sun Apr 10 11:25:11 EDT 2011

Merge branch 'master' of ssh://sox.git.sourceforge.net/gitroot/sox/sox

--- a/configure.ac
+++ b/configure.ac
@@ -590,7 +590,6 @@
 AM_CONDITIONAL(STATIC_LIBSOX_ONLY, test "$enable_shared" = "no" -a "$enable_static" = "yes")
 
 dnl Generate output files.
-AX_CREATE_STDINT_H(src/soxstdint.h)
 AC_CONFIG_FILES(Makefile src/Makefile libgsm/Makefile lpc10/Makefile msvc9/Makefile msvc10/Makefile sox.pc)
 AC_OUTPUT
 
--- a/m4/ax_create_stdint_h.m4
+++ /dev/null
@@ -1,734 +1,0 @@
-##### http://autoconf-archive.cryp.to/ax_create_stdint_h.html
-#
-# SYNOPSIS
-#
-#   AX_CREATE_STDINT_H [( HEADER-TO-GENERATE [, HEDERS-TO-CHECK])]
-#
-# DESCRIPTION
-#
-#   the "ISO C9X: 7.18 Integer types <stdint.h>" section requires the
-#   existence of an include file <stdint.h> that defines a set of
-#   typedefs, especially uint8_t,int32_t,uintptr_t. Many older
-#   installations will not provide this file, but some will have the
-#   very same definitions in <inttypes.h>. In other enviroments we can
-#   use the inet-types in <sys/types.h> which would define the typedefs
-#   int8_t and u_int8_t respectivly.
-#
-#   This macros will create a local "_stdint.h" or the headerfile given
-#   as an argument. In many cases that file will just "#include
-#   <stdint.h>" or "#include <inttypes.h>", while in other environments
-#   it will provide the set of basic 'stdint's definitions/typedefs:
-#
-#     int8_t,uint8_t,int16_t,uint16_t,int32_t,uint32_t,intptr_t,uintptr_t
-#     int_least32_t.. int_fast32_t.. intmax_t
-#
-#   which may or may not rely on the definitions of other files, or
-#   using the AC_CHECK_SIZEOF macro to determine the actual sizeof each
-#   type.
-#
-#   if your header files require the stdint-types you will want to
-#   create an installable file mylib-int.h that all your other
-#   installable header may include. So if you have a library package
-#   named "mylib", just use
-#
-#        AX_CREATE_STDINT_H(mylib-int.h)
-#
-#   in configure.ac and go to install that very header file in
-#   Makefile.am along with the other headers (mylib.h) - and the
-#   mylib-specific headers can simply use "#include <mylib-int.h>" to
-#   obtain the stdint-types.
-#
-#   Remember, if the system already had a valid <stdint.h>, the
-#   generated file will include it directly. No need for fuzzy
-#   HAVE_STDINT_H things... (oops, GCC 4.2.x has deliberatly disabled
-#   its stdint.h for non-c99 compilation and the c99-mode is not the
-#   default. Therefore this macro will not use the compiler's stdint.h
-#   - please complain to the GCC developers).
-#
-# LAST MODIFICATION
-#
-#   2006-10-13
-#
-# COPYLEFT
-#
-#   Copyright (c) 2006 Guido U. Draheim <guidod@gmx.de>
-#
-#   This program is free software; you can redistribute it and/or
-#   modify it under the terms of the GNU General Public License as
-#   published by the Free Software Foundation; either version 2 of the
-#   License, or (at your option) any later version.
-#
-#   This program is distributed in the hope that it will be useful, but
-#   WITHOUT ANY WARRANTY; without even the implied warranty of
-#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-#   General Public License for more details.
-#
-#   You should have received a copy of the GNU General Public License
-#   along with this program; if not, write to the Free Software
-#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-#   02111-1307, USA.
-#
-#   As a special exception, the respective Autoconf Macro's copyright
-#   owner gives unlimited permission to copy, distribute and modify the
-#   configure scripts that are the output of Autoconf when processing
-#   the Macro. You need not follow the terms of the GNU General Public
-#   License when using or distributing such scripts, even though
-#   portions of the text of the Macro appear in them. The GNU General
-#   Public License (GPL) does govern all other use of the material that
-#   constitutes the Autoconf Macro.
-#
-#   This special exception to the GPL applies to versions of the
-#   Autoconf Macro released by the Autoconf Macro Archive. When you
-#   make and distribute a modified version of the Autoconf Macro, you
-#   may extend this special exception to the GPL to apply to your
-#   modified version as well.
-
-AC_DEFUN([AX_CHECK_DATA_MODEL],[
-   AC_CHECK_SIZEOF(char)
-   AC_CHECK_SIZEOF(short)
-   AC_CHECK_SIZEOF(int)
-   AC_CHECK_SIZEOF(long)
-   AC_CHECK_SIZEOF(void*)
-   ac_cv_char_data_model=""
-   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_char"
-   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_short"
-   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_int"
-   ac_cv_long_data_model=""
-   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_int"
-   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_long"
-   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_voidp"
-   AC_MSG_CHECKING([data model])
-   case "$ac_cv_char_data_model/$ac_cv_long_data_model" in
-    122/242)     ac_cv_data_model="IP16"  ; n="standard 16bit machine" ;;
-    122/244)     ac_cv_data_model="LP32"  ; n="standard 32bit machine" ;;
-    122/*)       ac_cv_data_model="i16"   ; n="unusual int16 model" ;;
-    124/444)     ac_cv_data_model="ILP32" ; n="standard 32bit unixish" ;;
-    124/488)     ac_cv_data_model="LP64"  ; n="standard 64bit unixish" ;;
-    124/448)     ac_cv_data_model="LLP64" ; n="unusual 64bit unixish" ;;
-    124/*)       ac_cv_data_model="i32"   ; n="unusual int32 model" ;;
-    128/888)     ac_cv_data_model="ILP64" ; n="unusual 64bit numeric" ;;
-    128/*)       ac_cv_data_model="i64"   ; n="unusual int64 model" ;;
-    222/*2)      ac_cv_data_model="DSP16" ; n="strict 16bit dsptype" ;;
-    333/*3)      ac_cv_data_model="DSP24" ; n="strict 24bit dsptype" ;;
-    444/*4)      ac_cv_data_model="DSP32" ; n="strict 32bit dsptype" ;;
-    666/*6)      ac_cv_data_model="DSP48" ; n="strict 48bit dsptype" ;;
-    888/*8)      ac_cv_data_model="DSP64" ; n="strict 64bit dsptype" ;;
-    222/*|333/*|444/*|666/*|888/*) :
-                 ac_cv_data_model="iDSP"  ; n="unusual dsptype" ;;
-     *)          ac_cv_data_model="none"  ; n="very unusual model" ;;
-   esac
-   AC_MSG_RESULT([$ac_cv_data_model ($ac_cv_long_data_model, $n)])
-])
-
-dnl AX_CHECK_HEADER_STDINT_X([HEADERLIST][,ACTION-IF])
-AC_DEFUN([AX_CHECK_HEADER_STDINT_X],[
-AC_CACHE_CHECK([for stdint uintptr_t], [ac_cv_header_stdint_x],[
- ac_cv_header_stdint_x="" # the 1997 typedefs (inttypes.h)
-  AC_MSG_RESULT([(..)])
-  for i in m4_ifval([$1],[$1],[stdint.h inttypes.h sys/inttypes.h sys/types.h])
-  do
-   unset ac_cv_type_uintptr_t
-   unset ac_cv_type_uint64_t
-   AC_CHECK_TYPE(uintptr_t,[ac_cv_header_stdint_x=$i],continue,[#include <$i>])
-   AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>])
-   m4_ifvaln([$1],[$1]) break
-  done
-  AC_MSG_CHECKING([for stdint uintptr_t])
- ])
-])
-
-AC_DEFUN([AX_CHECK_HEADER_STDINT_O],[
-AC_CACHE_CHECK([for stdint uint32_t], [ac_cv_header_stdint_o],[
- ac_cv_header_stdint_o="" # the 1995 typedefs (sys/inttypes.h)
-  AC_MSG_RESULT([(..)])
-  for i in m4_ifval([$1],[$1],[inttypes.h sys/inttypes.h sys/types.h stdint.h])
-  do
-   unset ac_cv_type_uint32_t
-   unset ac_cv_type_uint64_t
-   AC_CHECK_TYPE(uint32_t,[ac_cv_header_stdint_o=$i],continue,[#include <$i>])
-   AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>])
-   m4_ifvaln([$1],[$1]) break
-   break;
-  done
-  AC_MSG_CHECKING([for stdint uint32_t])
- ])
-])
-
-AC_DEFUN([AX_CHECK_HEADER_STDINT_U],[
-AC_CACHE_CHECK([for stdint u_int32_t], [ac_cv_header_stdint_u],[
- ac_cv_header_stdint_u="" # the BSD typedefs (sys/types.h)
-  AC_MSG_RESULT([(..)])
-  for i in m4_ifval([$1],[$1],[sys/types.h inttypes.h sys/inttypes.h]) ; do
-   unset ac_cv_type_u_int32_t
-   unset ac_cv_type_u_int64_t
-   AC_CHECK_TYPE(u_int32_t,[ac_cv_header_stdint_u=$i],continue,[#include <$i>])
-   AC_CHECK_TYPE(u_int64_t,[and64="/u_int64_t"],[and64=""],[#include<$i>])
-   m4_ifvaln([$1],[$1]) break
-   break;
-  done
-  AC_MSG_CHECKING([for stdint u_int32_t])
- ])
-])
-
-AC_DEFUN([AX_CREATE_STDINT_H],
-[# ------ AX CREATE STDINT H -------------------------------------
-AC_MSG_CHECKING([for stdint types])
-ac_stdint_h=`echo ifelse($1, , _stdint.h, $1)`
-# try to shortcircuit - if the default include path of the compiler
-# can find a "stdint.h" header then we assume that all compilers can.
-AC_CACHE_VAL([ac_cv_header_stdint_t],[
-old_CXXFLAGS="$CXXFLAGS" ; CXXFLAGS=""
-old_CPPFLAGS="$CPPFLAGS" ; CPPFLAGS=""
-old_CFLAGS="$CFLAGS"     ; CFLAGS=""
-AC_TRY_COMPILE([#include <stdint.h>],[int_least32_t v = 0;],
-[ac_cv_stdint_result="(assuming C99 compatible system)"
- ac_cv_header_stdint_t="stdint.h"; ],
-[ac_cv_header_stdint_t=""])
-if test "$GCC" = "yes" && test ".$ac_cv_header_stdint_t" = "."; then
-CFLAGS="-std=c99"
-AC_TRY_COMPILE([#include <stdint.h>],[int_least32_t v = 0;],
-[AC_MSG_WARN(your GCC compiler has a defunct stdint.h for its default-mode)])
-fi
-CXXFLAGS="$old_CXXFLAGS"
-CPPFLAGS="$old_CPPFLAGS"
-CFLAGS="$old_CFLAGS" ])
-
-v="... $ac_cv_header_stdint_h"
-if test "$ac_stdint_h" = "stdint.h" ; then
- AC_MSG_RESULT([(are you sure you want them in ./stdint.h?)])
-elif test "$ac_stdint_h" = "inttypes.h" ; then
- AC_MSG_RESULT([(are you sure you want them in ./inttypes.h?)])
-elif test "_$ac_cv_header_stdint_t" = "_" ; then
- AC_MSG_RESULT([(putting them into $ac_stdint_h)$v])
-else
- ac_cv_header_stdint="$ac_cv_header_stdint_t"
- AC_MSG_RESULT([$ac_cv_header_stdint (shortcircuit)])
-fi
-
-if test "_$ac_cv_header_stdint_t" = "_" ; then # can not shortcircuit..
-
-dnl .....intro message done, now do a few system checks.....
-dnl btw, all old CHECK_TYPE macros do automatically "DEFINE" a type,
-dnl therefore we use the autoconf implementation detail CHECK_TYPE_NEW
-dnl instead that is triggered with 3 or more arguments (see types.m4)
-
-inttype_headers=`echo $2 | sed -e 's/,/ /g'`
-
-ac_cv_stdint_result="(no helpful system typedefs seen)"
-AX_CHECK_HEADER_STDINT_X(dnl
-   stdint.h inttypes.h sys/inttypes.h $inttype_headers,
-   ac_cv_stdint_result="(seen uintptr_t$and64 in $i)")
-
-if test "_$ac_cv_header_stdint_x" = "_" ; then
-AX_CHECK_HEADER_STDINT_O(dnl,
-   inttypes.h sys/inttypes.h stdint.h $inttype_headers,
-   ac_cv_stdint_result="(seen uint32_t$and64 in $i)")
-fi
-
-if test "_$ac_cv_header_stdint_x" = "_" ; then
-if test "_$ac_cv_header_stdint_o" = "_" ; then
-AX_CHECK_HEADER_STDINT_U(dnl,
-   sys/types.h inttypes.h sys/inttypes.h $inttype_headers,
-   ac_cv_stdint_result="(seen u_int32_t$and64 in $i)")
-fi fi
-
-dnl if there was no good C99 header file, do some typedef checks...
-if test "_$ac_cv_header_stdint_x" = "_" ; then
-   AC_MSG_CHECKING([for stdint datatype model])
-   AC_MSG_RESULT([(..)])
-   AX_CHECK_DATA_MODEL
-fi
-
-if test "_$ac_cv_header_stdint_x" != "_" ; then
-   ac_cv_header_stdint="$ac_cv_header_stdint_x"
-elif  test "_$ac_cv_header_stdint_o" != "_" ; then
-   ac_cv_header_stdint="$ac_cv_header_stdint_o"
-elif  test "_$ac_cv_header_stdint_u" != "_" ; then
-   ac_cv_header_stdint="$ac_cv_header_stdint_u"
-else
-   ac_cv_header_stdint="stddef.h"
-fi
-
-AC_MSG_CHECKING([for extra inttypes in chosen header])
-AC_MSG_RESULT([($ac_cv_header_stdint)])
-dnl see if int_least and int_fast types are present in _this_ header.
-unset ac_cv_type_int_least32_t
-unset ac_cv_type_int_fast32_t
-AC_CHECK_TYPE(int_least32_t,,,[#include <$ac_cv_header_stdint>])
-AC_CHECK_TYPE(int_fast32_t,,,[#include<$ac_cv_header_stdint>])
-AC_CHECK_TYPE(intmax_t,,,[#include <$ac_cv_header_stdint>])
-
-fi # shortcircut to system "stdint.h"
-# ------------------ PREPARE VARIABLES ------------------------------
-if test "$GCC" = "yes" ; then
-ac_cv_stdint_message="using gnu compiler "`$CC --version | head -1`
-else
-ac_cv_stdint_message="using $CC"
-fi
-
-AC_MSG_RESULT([make use of $ac_cv_header_stdint in $ac_stdint_h dnl
-$ac_cv_stdint_result])
-
-dnl -----------------------------------------------------------------
-# ----------------- DONE inttypes.h checks START header -------------
-AC_CONFIG_COMMANDS([$ac_stdint_h],[
-AC_MSG_NOTICE(creating $ac_stdint_h : $_ac_stdint_h)
-ac_stdint=$tmp/_stdint.h
-
-echo "#ifndef" $_ac_stdint_h >$ac_stdint
-echo "#define" $_ac_stdint_h "1" >>$ac_stdint
-echo "#ifndef" _GENERATED_STDINT_H >>$ac_stdint
-echo "#define" _GENERATED_STDINT_H '"'$PACKAGE $VERSION'"' >>$ac_stdint
-echo "/* generated $ac_cv_stdint_message */" >>$ac_stdint
-if test "_$ac_cv_header_stdint_t" != "_" ; then
-echo "#define _STDINT_HAVE_STDINT_H" "1" >>$ac_stdint
-echo "#include <stdint.h>" >>$ac_stdint
-echo "#endif" >>$ac_stdint
-echo "#endif" >>$ac_stdint
-else
-
-cat >>$ac_stdint <<STDINT_EOF
-
-/* ................... shortcircuit part ........................... */
-
-#if defined HAVE_STDINT_H || defined _STDINT_HAVE_STDINT_H
-#include <stdint.h>
-#else
-#include <stddef.h>
-
-/* .................... configured part ............................ */
-
-STDINT_EOF
-
-echo "/* whether we have a C99 compatible stdint header file */" >>$ac_stdint
-if test "_$ac_cv_header_stdint_x" != "_" ; then
-  ac_header="$ac_cv_header_stdint_x"
-  echo "#define _STDINT_HEADER_INTPTR" '"'"$ac_header"'"' >>$ac_stdint
-else
-  echo "/* #undef _STDINT_HEADER_INTPTR */" >>$ac_stdint
-fi
-
-echo "/* whether we have a C96 compatible inttypes header file */" >>$ac_stdint
-if  test "_$ac_cv_header_stdint_o" != "_" ; then
-  ac_header="$ac_cv_header_stdint_o"
-  echo "#define _STDINT_HEADER_UINT32" '"'"$ac_header"'"' >>$ac_stdint
-else
-  echo "/* #undef _STDINT_HEADER_UINT32 */" >>$ac_stdint
-fi
-
-echo "/* whether we have a BSD compatible inet types header */" >>$ac_stdint
-if  test "_$ac_cv_header_stdint_u" != "_" ; then
-  ac_header="$ac_cv_header_stdint_u"
-  echo "#define _STDINT_HEADER_U_INT32" '"'"$ac_header"'"' >>$ac_stdint
-else
-  echo "/* #undef _STDINT_HEADER_U_INT32 */" >>$ac_stdint
-fi
-
-echo "" >>$ac_stdint
-
-if test "_$ac_header" != "_" ; then if test "$ac_header" != "stddef.h" ; then
-  echo "#include <$ac_header>" >>$ac_stdint
-  echo "" >>$ac_stdint
-fi fi
-
-echo "/* which 64bit typedef has been found */" >>$ac_stdint
-if test "$ac_cv_type_uint64_t" = "yes" ; then
-echo "#define   _STDINT_HAVE_UINT64_T" "1"  >>$ac_stdint
-else
-echo "/* #undef _STDINT_HAVE_UINT64_T */" >>$ac_stdint
-fi
-if test "$ac_cv_type_u_int64_t" = "yes" ; then
-echo "#define   _STDINT_HAVE_U_INT64_T" "1"  >>$ac_stdint
-else
-echo "/* #undef _STDINT_HAVE_U_INT64_T */" >>$ac_stdint
-fi
-echo "" >>$ac_stdint
-
-echo "/* which type model has been detected */" >>$ac_stdint
-if test "_$ac_cv_char_data_model" != "_" ; then
-echo "#define   _STDINT_CHAR_MODEL" "$ac_cv_char_data_model" >>$ac_stdint
-echo "#define   _STDINT_LONG_MODEL" "$ac_cv_long_data_model" >>$ac_stdint
-else
-echo "/* #undef _STDINT_CHAR_MODEL // skipped */" >>$ac_stdint
-echo "/* #undef _STDINT_LONG_MODEL // skipped */" >>$ac_stdint
-fi
-echo "" >>$ac_stdint
-
-echo "/* whether int_least types were detected */" >>$ac_stdint
-if test "$ac_cv_type_int_least32_t" = "yes"; then
-echo "#define   _STDINT_HAVE_INT_LEAST32_T" "1"  >>$ac_stdint
-else
-echo "/* #undef _STDINT_HAVE_INT_LEAST32_T */" >>$ac_stdint
-fi
-echo "/* whether int_fast types were detected */" >>$ac_stdint
-if test "$ac_cv_type_int_fast32_t" = "yes"; then
-echo "#define   _STDINT_HAVE_INT_FAST32_T" "1" >>$ac_stdint
-else
-echo "/* #undef _STDINT_HAVE_INT_FAST32_T */" >>$ac_stdint
-fi
-echo "/* whether intmax_t type was detected */" >>$ac_stdint
-if test "$ac_cv_type_intmax_t" = "yes"; then
-echo "#define   _STDINT_HAVE_INTMAX_T" "1" >>$ac_stdint
-else
-echo "/* #undef _STDINT_HAVE_INTMAX_T */" >>$ac_stdint
-fi
-echo "" >>$ac_stdint
-
-  cat >>$ac_stdint <<STDINT_EOF
-/* .................... detections part ............................ */
-
-/* whether we need to define bitspecific types from compiler base types */
-#ifndef _STDINT_HEADER_INTPTR
-#ifndef _STDINT_HEADER_UINT32
-#ifndef _STDINT_HEADER_U_INT32
-#define _STDINT_NEED_INT_MODEL_T
-#else
-#define _STDINT_HAVE_U_INT_TYPES
-#endif
-#endif
-#endif
-
-#ifdef _STDINT_HAVE_U_INT_TYPES
-#undef _STDINT_NEED_INT_MODEL_T
-#endif
-
-#ifdef  _STDINT_CHAR_MODEL
-#if     _STDINT_CHAR_MODEL+0 == 122 || _STDINT_CHAR_MODEL+0 == 124
-#ifndef _STDINT_BYTE_MODEL
-#define _STDINT_BYTE_MODEL 12
-#endif
-#endif
-#endif
-
-#ifndef _STDINT_HAVE_INT_LEAST32_T
-#define _STDINT_NEED_INT_LEAST_T
-#endif
-
-#ifndef _STDINT_HAVE_INT_FAST32_T
-#define _STDINT_NEED_INT_FAST_T
-#endif
-
-#ifndef _STDINT_HEADER_INTPTR
-#define _STDINT_NEED_INTPTR_T
-#ifndef _STDINT_HAVE_INTMAX_T
-#define _STDINT_NEED_INTMAX_T
-#endif
-#endif
-
-
-/* .................... definition part ............................ */
-
-/* some system headers have good uint64_t */
-#ifndef _HAVE_UINT64_T
-#if     defined _STDINT_HAVE_UINT64_T  || defined HAVE_UINT64_T
-#define _HAVE_UINT64_T
-#elif   defined _STDINT_HAVE_U_INT64_T || defined HAVE_U_INT64_T
-#define _HAVE_UINT64_T
-typedef u_int64_t uint64_t;
-#endif
-#endif
-
-#ifndef _HAVE_UINT64_T
-/* .. here are some common heuristics using compiler runtime specifics */
-#if defined __STDC_VERSION__ && defined __STDC_VERSION__ >= 199901L
-#define _HAVE_UINT64_T
-#define _HAVE_LONGLONG_UINT64_T
-typedef long long int64_t;
-typedef unsigned long long uint64_t;
-
-#elif !defined __STRICT_ANSI__
-#if defined _MSC_VER || defined __WATCOMC__ || defined __BORLANDC__
-#define _HAVE_UINT64_T
-typedef __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-
-#elif defined __GNUC__ || defined __MWERKS__ || defined __ELF__
-/* note: all ELF-systems seem to have loff-support which needs 64-bit */
-#if !defined _NO_LONGLONG
-#define _HAVE_UINT64_T
-#define _HAVE_LONGLONG_UINT64_T
-typedef long long int64_t;
-typedef unsigned long long uint64_t;
-#endif
-
-#elif defined __alpha || (defined __mips && defined _ABIN32)
-#if !defined _NO_LONGLONG
-typedef long int64_t;
-typedef unsigned long uint64_t;
-#endif
-  /* compiler/cpu type to define int64_t */
-#endif
-#endif
-#endif
-
-#if defined _STDINT_HAVE_U_INT_TYPES
-/* int8_t int16_t int32_t defined by inet code, redeclare the u_intXX types */
-typedef u_int8_t uint8_t;
-typedef u_int16_t uint16_t;
-typedef u_int32_t uint32_t;
-
-/* glibc compatibility */
-#ifndef __int8_t_defined
-#define __int8_t_defined
-#endif
-#endif
-
-#ifdef _STDINT_NEED_INT_MODEL_T
-/* we must guess all the basic types. Apart from byte-adressable system, */
-/* there a few 32-bit-only dsp-systems that we guard with BYTE_MODEL 8-} */
-/* (btw, those nibble-addressable systems are way off, or so we assume) */
-
-dnl   /* have a look at "64bit and data size neutrality" at */
-dnl   /* http://unix.org/version2/whatsnew/login_64bit.html */
-dnl   /* (the shorthand "ILP" types always have a "P" part) */
-
-#if defined _STDINT_BYTE_MODEL
-#if _STDINT_LONG_MODEL+0 == 242
-/* 2:4:2 =  IP16 = a normal 16-bit system                */
-typedef unsigned char   uint8_t;
-typedef unsigned short  uint16_t;
-typedef unsigned long   uint32_t;
-#ifndef __int8_t_defined
-#define __int8_t_defined
-typedef          char    int8_t;
-typedef          short   int16_t;
-typedef          long    int32_t;
-#endif
-#elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL == 444
-/* 2:4:4 =  LP32 = a 32-bit system derived from a 16-bit */
-/* 4:4:4 = ILP32 = a normal 32-bit system                */
-typedef unsigned char   uint8_t;
-typedef unsigned short  uint16_t;
-typedef unsigned int    uint32_t;
-#ifndef __int8_t_defined
-#define __int8_t_defined
-typedef          char    int8_t;
-typedef          short   int16_t;
-typedef          int     int32_t;
-#endif
-#elif _STDINT_LONG_MODEL+0 == 484 || _STDINT_LONG_MODEL+0 == 488
-/* 4:8:4 =  IP32 = a 32-bit system prepared for 64-bit    */
-/* 4:8:8 =  LP64 = a normal 64-bit system                 */
-typedef unsigned char   uint8_t;
-typedef unsigned short  uint16_t;
-typedef unsigned int    uint32_t;
-#ifndef __int8_t_defined
-#define __int8_t_defined
-typedef          char    int8_t;
-typedef          short   int16_t;
-typedef          int     int32_t;
-#endif
-/* this system has a "long" of 64bit */
-#ifndef _HAVE_UINT64_T
-#define _HAVE_UINT64_T
-typedef unsigned long   uint64_t;
-typedef          long    int64_t;
-#endif
-#elif _STDINT_LONG_MODEL+0 == 448
-/*      LLP64   a 64-bit system derived from a 32-bit system */
-typedef unsigned char   uint8_t;
-typedef unsigned short  uint16_t;
-typedef unsigned int    uint32_t;
-#ifndef __int8_t_defined
-#define __int8_t_defined
-typedef          char    int8_t;
-typedef          short   int16_t;
-typedef          int     int32_t;
-#endif
-/* assuming the system has a "long long" */
-#ifndef _HAVE_UINT64_T
-#define _HAVE_UINT64_T
-#define _HAVE_LONGLONG_UINT64_T
-typedef unsigned long long uint64_t;
-typedef          long long  int64_t;
-#endif
-#else
-#define _STDINT_NO_INT32_T
-#endif
-#else
-#define _STDINT_NO_INT8_T
-#define _STDINT_NO_INT32_T
-#endif
-#endif
-
-/*
- * quote from SunOS-5.8 sys/inttypes.h:
- * Use at your own risk.  As of February 1996, the committee is squarely
- * behind the fixed sized types; the "least" and "fast" types are still being
- * discussed.  The probability that the "fast" types may be removed before
- * the standard is finalized is high enough that they are not currently
- * implemented.
- */
-
-#if defined _STDINT_NEED_INT_LEAST_T
-typedef  int8_t    int_least8_t;
-typedef  int16_t   int_least16_t;
-typedef  int32_t   int_least32_t;
-#ifdef _HAVE_UINT64_T
-typedef  int64_t   int_least64_t;
-#endif
-
-typedef uint8_t   uint_least8_t;
-typedef uint16_t  uint_least16_t;
-typedef uint32_t  uint_least32_t;
-#ifdef _HAVE_UINT64_T
-typedef uint64_t  uint_least64_t;
-#endif
-  /* least types */
-#endif
-
-#if defined _STDINT_NEED_INT_FAST_T
-typedef  int8_t    int_fast8_t;
-typedef  int       int_fast16_t;
-typedef  int32_t   int_fast32_t;
-#ifdef _HAVE_UINT64_T
-typedef  int64_t   int_fast64_t;
-#endif
-
-typedef uint8_t   uint_fast8_t;
-typedef unsigned  uint_fast16_t;
-typedef uint32_t  uint_fast32_t;
-#ifdef _HAVE_UINT64_T
-typedef uint64_t  uint_fast64_t;
-#endif
-  /* fast types */
-#endif
-
-#ifdef _STDINT_NEED_INTMAX_T
-#ifdef _HAVE_UINT64_T
-typedef  int64_t       intmax_t;
-typedef uint64_t      uintmax_t;
-#else
-typedef          long  intmax_t;
-typedef unsigned long uintmax_t;
-#endif
-#endif
-
-#ifdef _STDINT_NEED_INTPTR_T
-#ifndef __intptr_t_defined
-#define __intptr_t_defined
-/* we encourage using "long" to store pointer values, never use "int" ! */
-#if   _STDINT_LONG_MODEL+0 == 242 || _STDINT_LONG_MODEL+0 == 484
-typedef  unsigned int   uintptr_t;
-typedef           int    intptr_t;
-#elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL+0 == 444
-typedef  unsigned long  uintptr_t;
-typedef           long   intptr_t;
-#elif _STDINT_LONG_MODEL+0 == 448 && defined _HAVE_UINT64_T
-typedef        uint64_t uintptr_t;
-typedef         int64_t  intptr_t;
-#else /* matches typical system types ILP32 and LP64 - but not IP16 or LLP64 */
-typedef  unsigned long  uintptr_t;
-typedef           long   intptr_t;
-#endif
-#endif
-#endif
-
-/* The ISO C99 standard specifies that in C++ implementations these
-   should only be defined if explicitly requested.  */
-#if !defined __cplusplus || defined __STDC_CONSTANT_MACROS
-#ifndef UINT32_C
-
-/* Signed.  */
-# define INT8_C(c)      c
-# define INT16_C(c)     c
-# define INT32_C(c)     c
-# ifdef _HAVE_LONGLONG_UINT64_T
-#  define INT64_C(c)    c ## L
-# else
-#  define INT64_C(c)    c ## LL
-# endif
-
-/* Unsigned.  */
-# define UINT8_C(c)     c ## U
-# define UINT16_C(c)    c ## U
-# define UINT32_C(c)    c ## U
-# ifdef _HAVE_LONGLONG_UINT64_T
-#  define UINT64_C(c)   c ## UL
-# else
-#  define UINT64_C(c)   c ## ULL
-# endif
-
-/* Maximal type.  */
-# ifdef _HAVE_LONGLONG_UINT64_T
-#  define INTMAX_C(c)   c ## L
-#  define UINTMAX_C(c)  c ## UL
-# else
-#  define INTMAX_C(c)   c ## LL
-#  define UINTMAX_C(c)  c ## ULL
-# endif
-
-  /* literalnumbers */
-#endif
-#endif
-
-/* These limits are merily those of a two complement byte-oriented system */
-
-/* Minimum of signed integral types.  */
-# define INT8_MIN               (-128)
-# define INT16_MIN              (-32767-1)
-# define INT32_MIN              (-2147483647-1)
-# define INT64_MIN              (-9223372036854775807LL-1)
-/* Maximum of signed integral types.  */
-# define INT8_MAX               (127)
-# define INT16_MAX              (32767)
-# define INT32_MAX              (2147483647)
-# define INT64_MAX              (9223372036854775807LL)
-
-/* Maximum of unsigned integral types.  */
-# define UINT8_MAX              (255U)
-# define UINT16_MAX             (65535U)
-# define UINT32_MAX             (4294967295U)
-# define UINT64_MAX             (18446744073709551615ULL)
-
-/* Minimum of signed integral types having a minimum size.  */
-# define INT_LEAST8_MIN         INT8_MIN
-# define INT_LEAST16_MIN        INT16_MIN
-# define INT_LEAST32_MIN        INT32_MIN
-# define INT_LEAST64_MIN        INT64_MIN
-/* Maximum of signed integral types having a minimum size.  */
-# define INT_LEAST8_MAX         INT8_MAX
-# define INT_LEAST16_MAX        INT16_MAX
-# define INT_LEAST32_MAX        INT32_MAX
-# define INT_LEAST64_MAX        INT64_MAX
-
-/* Maximum of unsigned integral types having a minimum size.  */
-# define UINT_LEAST8_MAX        UINT8_MAX
-# define UINT_LEAST16_MAX       UINT16_MAX
-# define UINT_LEAST32_MAX       UINT32_MAX
-# define UINT_LEAST64_MAX       UINT64_MAX
-
-  /* shortcircuit*/
-#endif
-  /* once */
-#endif
-#endif
-STDINT_EOF
-fi
-    if cmp -s $ac_stdint_h $ac_stdint 2>/dev/null; then
-      AC_MSG_NOTICE([$ac_stdint_h is unchanged])
-    else
-      ac_dir=`AS_DIRNAME(["$ac_stdint_h"])`
-      AS_MKDIR_P(["$ac_dir"])
-      rm -f $ac_stdint_h
-      mv $ac_stdint $ac_stdint_h
-    fi
-],[# variables for create stdint.h replacement
-PACKAGE="$PACKAGE"
-VERSION="$VERSION"
-ac_stdint_h="$ac_stdint_h"
-_ac_stdint_h=AS_TR_CPP(_$PACKAGE-$ac_stdint_h)
-ac_cv_stdint_message="$ac_cv_stdint_message"
-ac_cv_header_stdint_t="$ac_cv_header_stdint_t"
-ac_cv_header_stdint_x="$ac_cv_header_stdint_x"
-ac_cv_header_stdint_o="$ac_cv_header_stdint_o"
-ac_cv_header_stdint_u="$ac_cv_header_stdint_u"
-ac_cv_type_uint64_t="$ac_cv_type_uint64_t"
-ac_cv_type_u_int64_t="$ac_cv_type_u_int64_t"
-ac_cv_char_data_model="$ac_cv_char_data_model"
-ac_cv_long_data_model="$ac_cv_long_data_model"
-ac_cv_type_int_least32_t="$ac_cv_type_int_least32_t"
-ac_cv_type_int_fast32_t="$ac_cv_type_int_fast32_t"
-ac_cv_type_intmax_t="$ac_cv_type_intmax_t"
-])
-])
--- a/msvc10/LibSoX.vcxproj
+++ b/msvc10/LibSoX.vcxproj
@@ -122,7 +122,6 @@
     <ClInclude Include="..\src\rate_poly_fir.h" />
     <ClInclude Include="..\src\rate_poly_fir0.h" />
     <ClInclude Include="..\src\raw.h" />
-    <ClInclude Include="..\src\sgetopt.h" />
     <ClInclude Include="..\src\sox.h" />
     <ClInclude Include="..\src\sox_i.h" />
     <ClInclude Include="..\src\sox_sample_test.h" />
@@ -333,7 +332,6 @@
     <ClCompile Include="..\src\g723_40.c" />
     <ClCompile Include="..\src\g72x.c" />
     <ClCompile Include="..\src\getopt.c" />
-    <ClCompile Include="..\src\getopt1.c" />
     <ClCompile Include="..\src\libsox.c" />
     <ClCompile Include="..\src\libsox_i.c" />
     <ClCompile Include="..\src\raw.c" />
--- a/msvc10/LibSoX.vcxproj.filters
+++ b/msvc10/LibSoX.vcxproj.filters
@@ -106,9 +106,6 @@
     <ClInclude Include="..\src\raw.h">
       <Filter>Headers</Filter>
     </ClInclude>
-    <ClInclude Include="..\src\sgetopt.h">
-      <Filter>Headers</Filter>
-    </ClInclude>
     <ClInclude Include="..\src\sox.h">
       <Filter>Headers</Filter>
     </ClInclude>
@@ -589,9 +586,6 @@
       <Filter>Shared Sources</Filter>
     </ClCompile>
     <ClCompile Include="..\src\getopt.c">
-      <Filter>Shared Sources</Filter>
-    </ClCompile>
-    <ClCompile Include="..\src\getopt1.c">
       <Filter>Shared Sources</Filter>
     </ClCompile>
     <ClCompile Include="..\src\libsox.c">
--- a/msvc9/LibSoX.vcproj
+++ b/msvc9/LibSoX.vcproj
@@ -280,10 +280,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\src\sgetopt.h"
-				>
-			</File>
-			<File
 				RelativePath="..\src\sox.h"
 				>
 			</File>
@@ -1197,10 +1193,6 @@
 			</File>
 			<File
 				RelativePath="..\src\getopt.c"
-				>
-			</File>
-			<File
-				RelativePath="..\src\getopt1.c"
 				>
 			</File>
 			<File
--- a/src/.gitignore
+++ b/src/.gitignore
@@ -4,7 +4,6 @@
 example?
 soxconfig.h.in
 soxconfig.h
-soxstdint.h
 .deps
 stamp-h1
 .libs
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -57,7 +57,7 @@
   effects                 formats_i               libsox_i
   effects_i               ${formats_srcs}         ${optional_srcs}
   effects_i_dsp           getopt
-  ${effects_srcs}         getopt1                 util
+  ${effects_srcs}         util
   formats                 libsox                  xmalloc
 )
 add_executable(${PROJECT_NAME} ${PROJECT_NAME}.c)
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -61,7 +61,7 @@
 libsox_la_SOURCES = adpcms.c adpcms.h aiff.c aiff.h cvsd.c cvsd.h cvsdfilt.h \
 	  g711.c g711.h g721.c g723_24.c g723_40.c g72x.c g72x.h vox.c vox.h \
 	  raw.c raw.h formats.c formats.h formats_i.c sox_i.h skelform.c \
-	  xmalloc.c xmalloc.h getopt.c getopt1.c sgetopt.h \
+	  xmalloc.c xmalloc.h getopt.c \
 	  util.c util.h libsox.c libsox_i.c sox-fmt.c soxomp.h
 
 # Effects source
--- a/src/bend.c
+++ b/src/bend.c
@@ -33,7 +33,6 @@
 #endif
 
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <assert.h>
 
 #define MAX_FRAME_LENGTH 8192
@@ -98,15 +97,17 @@
   priv_t *p = (priv_t *) effp->priv;
   char const * opts = "f:o:";
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, opts, NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->frame_rate = 25;
   p->ovsamp = 16;
-  while ((c = lsx_getopt(argc, argv, opts)) != -1) switch (c) {
-    GETOPT_NUMERIC('f', frame_rate, 10 , 80)
-    GETOPT_NUMERIC('o', ovsamp,  4 , 32)
-    default: lsx_fail("unknown option `-%c'", optopt); return lsx_usage(effp);
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
+    GETOPT_NUMERIC(optstate, 'f', frame_rate, 10 , 80)
+    GETOPT_NUMERIC(optstate, 'o', ovsamp,  4 , 32)
+    default: lsx_fail("unknown option `-%c'", optstate.opt); return lsx_usage(effp);
   }
-  argc -= lsx_optind, argv += lsx_optind;
+  argc -= optstate.ind, argv += optstate.ind;
 
   p->bends = lsx_calloc(p->nbends = argc, sizeof(*p->bends));
   return parse(effp, argv, 0.);     /* No rate yet; parse with dummy */
--- a/src/dither.c
+++ b/src/dither.c
@@ -20,7 +20,6 @@
 #endif
 
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <assert.h>
 
 #undef RANQD1
@@ -329,20 +328,22 @@
 {
   priv_t * p = (priv_t *)effp->priv;
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, "+aSsf:rt", NULL, lsx_getopt_flag_none, 1, &optstate);
 
-  while ((c = lsx_getopt(argc, argv, "+aSsf:""rt")) != -1) switch (c) {
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
     case 'a': p->auto_detect = sox_true; break;
     case 'S': p->alt_tpdf = sox_true; break;
     case 'r': case 't': break; /* No longer in use */
     case 's': p->filter_name = Shape_shibata; break;
     case 'f':
-      p->filter_name = lsx_enum_option(c, filter_names);
+      p->filter_name = lsx_enum_option(c, optstate.arg, filter_names);
       if (p->filter_name == INT_MAX)
         return SOX_EOF;
       break;
-    default: lsx_fail("invalid option `-%c'", optopt); return lsx_usage(effp);
+    default: lsx_fail("invalid option `-%c'", optstate.opt); return lsx_usage(effp);
   }
-  argc -= lsx_optind, argv += lsx_optind;
+  argc -= optstate.ind, argv += optstate.ind;
   do {NUMERIC_PARAMETER(dummy, 0.5, 1)} while (0); /* No longer in use */
   return argc? lsx_usage(effp) : SOX_SUCCESS;
 }
--- a/src/effects.c
+++ b/src/effects.c
@@ -17,7 +17,6 @@
 
 #define LSX_EFF_ALIAS
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <assert.h>
 #include <string.h>
 #ifdef HAVE_STRINGS_H
@@ -77,14 +76,12 @@
 
 int sox_effect_options(sox_effect_t *effp, int argc, char * const argv[])
 {
-  int result, callers_optind = lsx_optind, callers_opterr = opterr;
+  int result;
 
   char * * argv2 = lsx_malloc((argc + 1) * sizeof(*argv2));
   argv2[0] = (char *)effp->handler.name;
   memcpy(argv2 + 1, argv, argc * sizeof(*argv2));
-  lsx_optind = 1, opterr = 0;
   result = effp->handler.getopts(effp, argc + 1, argv2);
-  lsx_optind = callers_optind, opterr = callers_opterr;
   free(argv2);
   return result;
 } /* sox_effect_options */
--- a/src/getopt.c
+++ b/src/getopt.c
@@ -1,12 +1,7 @@
-#include "soxconfig.h"
-/* Getopt for GNU.
-   NOTE: getopt is now part of the C library, so if you don't know what
-   "Keep this file name-space clean" means, talk to drepper@gnu.org
-   before changing it!
-   Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002
-        Free Software Foundation, Inc.
-   This file is part of the GNU C Library.
-
+/* lsx_getopt for SoX
+ *
+ * (c) 2011 Doug Cook and SoX contributors
+ *
  * This library is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as published by
  * the Free Software Foundation; either version 2.1 of the License, or (at
@@ -21,1277 +16,334 @@
  * along with this library; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  */
-
-/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
-   Ditto for AIX 3.2 and <stdlib.h>.  */
-#ifndef _NO_PROTO
-# define _NO_PROTO
-#endif
 
-#if 0
-#ifdef HAVE_CONFIG_H
-# include <config.h>
-#endif
-#endif
+#include "sox.h"
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
 
-#if !defined __STDC__ || !__STDC__
-/* This is a separate conditional since some stdc systems
-   reject `defined (const)'.  */
-# ifndef const
-#  define const
-# endif
-#endif
-
-#include <stdio.h>
-
-/* Comment out all this code if we are using the GNU C Library, and are not
-   actually compiling the library itself.  This code is part of the GNU C
-   Library, but also included in many other GNU distributions.  Compiling
-   and linking in this code is a waste when using the GNU C library
-   (especially if it is a shared library).  Rather than having every GNU
-   program understand `configure --with-gnu-libc' and omit the object files,
-   it is simpler to just do this in the source for each such file.  */
-
-#define GETOPT_INTERFACE_VERSION 2
-#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
-# include <gnu-versions.h>
-# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
-#  define ELIDE_CODE
-# endif
-#endif
-
-/* Always compile for SoX. */
-#undef ELIDE_CODE
-
-#ifndef ELIDE_CODE
-
-
-/* This needs to come after some library #include
-   to get __GNU_LIBRARY__ defined.  */
-#ifdef  __GNU_LIBRARY__
-/* Don't include stdlib.h for non-GNU C libraries because some of them
-   contain conflicting prototypes for getopt.  */
-# include <stdlib.h>
-# include <unistd.h>
-#endif  /* GNU C library.  */
-
-#ifdef VMS
-# include <unixlib.h>
-# if HAVE_STRING_H - 0
-#  include <string.h>
-# endif
-#endif
-
-#ifndef _
-/* This is for other GNU distributions with internationalized messages.  */
-# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
-#  include <libintl.h>
-#  ifndef _
-#   define _(msgid)     gettext (msgid)
-#  endif
-# else
-#  define _(msgid)      (msgid)
-# endif
-# if defined _LIBC && defined USE_IN_LIBIO
-#  include <wchar.h>
-# endif
-#endif
-
-#ifndef attribute_hidden
-# define attribute_hidden
-#endif
-
-/* This version of `getopt' appears to the caller like standard Unix `getopt'
-   but it behaves differently for the user, since it allows the user
-   to intersperse the options with the other arguments.
-
-   As `getopt' works, it permutes the elements of ARGV so that,
-   when it is done, all the options precede everything else.  Thus
-   all application programs are extended to handle flexible argument order.
-
-   Setting the environment variable POSIXLY_CORRECT disables permutation.
-   Then the behavior is completely standard.
-
-   GNU application programs can use a third alternative mode in which
-   they can distinguish the relative order of options and other arguments.  */
-
-#if 0
- #ifdef _LIBC
- # include <getopt.h>
- #else
- # include "getopt.h"
- #endif
-#endif
-#include "sgetopt.h"
-
-/* For communication from `getopt' to the caller.
-   When `getopt' finds an option that takes an argument,
-   the argument value is returned here.
-   Also, when `ordering' is RETURN_IN_ORDER,
-   each non-option ARGV-element is returned here.  */
-
-char *lsx_optarg = NULL;
-
-/* Index in ARGV of the next element to be scanned.
-   This is used for communication to and from the caller
-   and for communication between successive calls to `getopt'.
-
-   On entry to `getopt', zero means this is the first call; initialize.
-
-   When `getopt' returns -1, this is the index of the first of the
-   non-option elements that the caller should itself scan.
-
-   Otherwise, `optind' communicates from one call to the next
-   how much of ARGV has been scanned so far.  */
-
-/* 1003.2 says this must be 1 before any call.  */
-int lsx_optind = 1;
-
-/* Formerly, initialization of getopt depended on optind==0, which
-   causes problems with re-calling getopt as programs generally don't
-   know that. */
-
-int __getopt_initialized attribute_hidden;
-
-/* The next char to be scanned in the option-element
-   in which the last option character we returned was found.
-   This allows us to pick up the scan where we left off.
-
-   If this is zero, or a null string, it means resume the scan
-   by advancing to the next ARGV-element.  */
-
-static char *nextchar;
-
-/* Callers store zero here to inhibit the error message
-   for unrecognized options.  */
-
-int opterr = 1;
-
-/* Set to an option character which was unrecognized.
-   This must be initialized on some systems to avoid linking in the
-   system's own getopt implementation.  */
-
-int optopt = '?';
-
-/* Describe how to deal with options that follow non-option ARGV-elements.
-
-   If the caller did not specify anything,
-   the default is REQUIRE_ORDER if the environment variable
-   POSIXLY_CORRECT is defined, PERMUTE otherwise.
-
-   REQUIRE_ORDER means don't recognize them as options;
-   stop option processing when the first non-option is seen.
-   This is what Unix does.
-   This mode of operation is selected by either setting the environment
-   variable POSIXLY_CORRECT, or using `+' as the first character
-   of the list of option characters.
-
-   PERMUTE is the default.  We permute the contents of ARGV as we scan,
-   so that eventually all the non-options are at the end.  This allows options
-   to be given in any order, even with programs that were not written to
-   expect this.
-
-   RETURN_IN_ORDER is an option available to programs that were written
-   to expect options and other ARGV-elements in any order and that care about
-   the ordering of the two.  We describe each non-option ARGV-element
-   as if it were the argument of an option with character code 1.
-   Using `-' as the first character of the list of option characters
-   selects this mode of operation.
-
-   The special argument `--' forces an end of option-scanning regardless
-   of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
-   `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
-
-static enum
+void
+SOX_API lsx_getopt_init(
+    LSX_PARAM_IN             int argc,                      /* Number of arguments in argv */
+    LSX_PARAM_IN_COUNT(argc) char * const * argv,           /* Array of arguments */
+    LSX_PARAM_IN_Z           char const * shortopts,        /* Short option characters */
+    LSX_PARAM_IN_OPT         lsx_option_t const * longopts, /* Array of long option descriptors */
+    LSX_PARAM_IN             lsx_getopt_flags_t flags,      /* Flags for longonly and opterr */
+    LSX_PARAM_IN             int first,                     /* First argument to check (usually 1) */
+    LSX_PARAM_OUT            lsx_getopt_t * state)          /* State object to initialize */
 {
-  REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
-} ordering;
-
-/* Value of POSIXLY_CORRECT environment variable.  */
-static char *posixly_correct;
-
-#ifdef  __GNU_LIBRARY__
-/* We want to avoid inclusion of string.h with non-GNU libraries
-   because there are many ways it can cause trouble.
-   On some systems, it contains special magic macros that don't work
-   in GCC.  */
-# include <string.h>
-# define my_index       strchr
-#else
-
-# if HAVE_STRING_H
-#  include <string.h>
-# else
-#  include <strings.h>
-# endif
-
-/* Avoid depending on library functions or files
-   whose names are inconsistent.  */
-
-#ifndef getenv
-extern char *getenv (char const *);
-#endif
-
-static char *
-my_index (char const * str, int chr)
-{
-  while (*str)
+    assert(argc >= 0);
+    assert(argv != NULL);
+    assert(shortopts);
+    assert(first >= 0);
+    assert(first <= argc);
+    assert(state);
+    if (state)
     {
-      if (*str == chr)
-        return (char *) str;
-      str++;
-    }
-  return 0;
-}
-
-/* If using GCC, we can safely declare strlen this way.
-   If not using GCC, it is ok not to declare it.  */
-#ifdef __GNUC__
-/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
-   That was relevant to code that was here before.  */
-# if (!defined __STDC__ || !__STDC__) && !defined strlen
-/* gcc with -traditional declares the built-in strlen to return int,
-   and has done so at least since version 2.4.5. -- rms.  */
-extern int strlen (const char *);
-# endif /* not __STDC__ */
-#endif /* __GNUC__ */
-
-#endif /* not __GNU_LIBRARY__ */
-
-/* Handle permutation of arguments.  */
-
-/* Describe the part of ARGV that contains non-options that have
-   been skipped.  `first_nonopt' is the index in ARGV of the first of them;
-   `last_nonopt' is the index after the last of them.  */
-
-static int first_nonopt;
-static int last_nonopt;
-
-#ifdef _LIBC
-/* Stored original parameters.
-   XXX This is no good solution.  We should rather copy the args so
-   that we can compare them later.  But we must not use malloc(3).  */
-extern int __libc_argc;
-extern char **__libc_argv;
-
-/* Bash 2.0 gives us an environment variable containing flags
-   indicating ARGV elements that should not be considered arguments.  */
-
-# ifdef USE_NONOPTION_FLAGS
-/* Defined in getopt_init.c  */
-extern char *__getopt_nonoption_flags;
-
-static int nonoption_flags_max_len;
-static int nonoption_flags_len;
-# endif
-
-# ifdef USE_NONOPTION_FLAGS
-#  define SWAP_FLAGS(ch1, ch2) \
-  if (nonoption_flags_len > 0)                                                \
-    {                                                                         \
-      char __tmp = __getopt_nonoption_flags[ch1];                             \
-      __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
-      __getopt_nonoption_flags[ch2] = __tmp;                                  \
-    }
-# else
-#  define SWAP_FLAGS(ch1, ch2)
-# endif
-#else   /* !_LIBC */
-# define SWAP_FLAGS(ch1, ch2)
-#endif  /* _LIBC */
-
-/* Exchange two adjacent subsequences of ARGV.
-   One subsequence is elements [first_nonopt,last_nonopt)
-   which contains all the non-options that have been skipped so far.
-   The other is elements [last_nonopt,optind), which contains all
-   the options processed since those non-options were skipped.
-
-   `first_nonopt' and `last_nonopt' are relocated so that they describe
-   the new indices of the non-options in ARGV after they are moved.  */
-
-#if defined __STDC__ && __STDC__
-static void exchange (char **);
-#endif
-
-static void
-exchange (argv)
-     char **argv;
-{
-  int bottom = first_nonopt;
-  int middle = last_nonopt;
-  int top = lsx_optind;
-  char *tem;
-
-  /* Exchange the shorter segment with the far end of the longer segment.
-     That puts the shorter segment into the right place.
-     It leaves the longer segment in the right place overall,
-     but it consists of two parts that need to be swapped next.  */
-
-#if defined _LIBC && defined USE_NONOPTION_FLAGS
-  /* First make sure the handling of the `__getopt_nonoption_flags'
-     string can work normally.  Our top argument must be in the range
-     of the string.  */
-  if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
-    {
-      /* We must extend the array.  The user plays games with us and
-         presents new arguments.  */
-      char *new_str = lsx_malloc (top + 1);
-      if (new_str == NULL)
-        nonoption_flags_len = nonoption_flags_max_len = 0;
-      else
+        if (argc < 0 ||
+            !argv ||
+            !shortopts ||
+            first < 0 ||
+            first > argc)
         {
-          memset (__mempcpy (new_str, __getopt_nonoption_flags,
-                             nonoption_flags_max_len),
-                  '\0', top + 1 - nonoption_flags_max_len);
-          nonoption_flags_max_len = top + 1;
-          __getopt_nonoption_flags = new_str;
+            memset(state, 0, sizeof(*state));
         }
-    }
-#endif
-
-  while (top > middle && middle > bottom)
-    {
-      if (top - middle > middle - bottom)
+        else
         {
-          /* Bottom segment is the short one.  */
-          int len = middle - bottom;
-          register int i;
-
-          /* Swap it with the top part of the top segment.  */
-          for (i = 0; i < len; i++)
-            {
-              tem = argv[bottom + i];
-              argv[bottom + i] = argv[top - (middle - bottom) + i];
-              argv[top - (middle - bottom) + i] = tem;
-              SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
-            }
-          /* Exclude the moved bottom segment from further swapping.  */
-          top -= len;
+            state->argc = argc;
+            state->argv = argv;
+            state->shortopts =
+                (shortopts[0] == '+' || shortopts[0] == '-') /* Requesting GNU special behavior? */
+                ? shortopts + 1 /* Ignore request. */
+                : shortopts; /* No special behavior requested. */
+            state->longopts = longopts;
+            state->flags = flags;
+            state->curpos = NULL;
+            state->ind = first;
+            state->opt = '?';
+            state->arg = NULL;
+            state->lngind = -1;
         }
-      else
-        {
-          /* Top segment is the short one.  */
-          int len = top - middle;
-          register int i;
-
-          /* Swap it with the bottom part of the bottom segment.  */
-          for (i = 0; i < len; i++)
-            {
-              tem = argv[bottom + i];
-              argv[bottom + i] = argv[middle + i];
-              argv[middle + i] = tem;
-              SWAP_FLAGS (bottom + i, middle + i);
-            }
-          /* Exclude the moved top segment from further swapping.  */
-          bottom += len;
-        }
     }
-
-  /* Update records for the slots the non-options now occupy.  */
-
-  first_nonopt += (lsx_optind - last_nonopt);
-  last_nonopt = lsx_optind;
 }
 
-/* Initialize the internal data when the first call is made.  */
-
-#if defined __STDC__ && __STDC__
-static const char *_getopt_initialize (int, char *const *, const char *);
-#endif
-static const char *
-_getopt_initialize (argc, argv, optstring)
-     int argc;
-     char *const *argv;
-     const char *optstring;
+static void CheckCurPosEnd(
+    LSX_PARAM_INOUT lsx_getopt_t * state)
 {
-  /* Start processing options with ARGV-element 1 (since ARGV-element 0
-     is the program name); the sequence of previously skipped
-     non-option ARGV-elements is empty.  */
-
-  first_nonopt = last_nonopt = lsx_optind;
-
-  nextchar = NULL;
-
-  posixly_correct = getenv ("POSIXLY_CORRECT");
-
-  /* Determine how to handle the ordering of options and nonoptions.  */
-
-  if (optstring[0] == '-')
+    if (!state->curpos[0])
     {
-      ordering = RETURN_IN_ORDER;
-      ++optstring;
+        state->curpos = NULL;
+        state->ind++;
     }
-  else if (optstring[0] == '+')
-    {
-      ordering = REQUIRE_ORDER;
-      ++optstring;
-    }
-  else if (posixly_correct != NULL)
-    ordering = REQUIRE_ORDER;
-  else
-    ordering = PERMUTE;
-
-#if defined _LIBC && defined USE_NONOPTION_FLAGS
-  if (posixly_correct == NULL
-      && argc == __libc_argc && argv == __libc_argv)
-    {
-      if (nonoption_flags_max_len == 0)
-        {
-          if (__getopt_nonoption_flags == NULL
-              || __getopt_nonoption_flags[0] == '\0')
-            nonoption_flags_max_len = -1;
-          else
-            {
-              const char *orig_str = __getopt_nonoption_flags;
-              int len = nonoption_flags_max_len = strlen (orig_str);
-              if (nonoption_flags_max_len < argc)
-                nonoption_flags_max_len = argc;
-              __getopt_nonoption_flags =
-                lsx_malloc (nonoption_flags_max_len);
-              if (__getopt_nonoption_flags == NULL)
-                nonoption_flags_max_len = -1;
-              else
-                memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
-                        '\0', nonoption_flags_max_len - len);
-            }
-        }
-      nonoption_flags_len = nonoption_flags_max_len;
-    }
-  else
-    nonoption_flags_len = 0;
-#else
-  (void)argc, (void)argv;
-#endif
-
-  return optstring;
 }
-
-/* Scan elements of ARGV (whose length is ARGC) for option characters
-   given in OPTSTRING.
 
-   If an element of ARGV starts with '-', and is not exactly "-" or "--",
-   then it is an option element.  The characters of this element
-   (aside from the initial '-') are option characters.  If `getopt'
-   is called repeatedly, it returns successively each of the option characters
-   from each of the option elements.
-
-   If `getopt' finds another option character, it returns that character,
-   updating `optind' and `nextchar' so that the next call to `getopt' can
-   resume the scan with the following option character or ARGV-element.
-
-   If there are no more option characters, `getopt' returns -1.
-   Then `optind' is the index in ARGV of the first ARGV-element
-   that is not an option.  (The ARGV-elements have been permuted
-   so that those that are not options now come last.)
-
-   OPTSTRING is a string containing the legitimate option characters.
-   If an option character is seen that is not listed in OPTSTRING,
-   return '?' after printing an error message.  If you set `opterr' to
-   zero, the error message is suppressed but we still return '?'.
-
-   If a char in OPTSTRING is followed by a colon, that means it wants an arg,
-   so the following text in the same ARGV-element, or the text of the following
-   ARGV-element, is returned in `optarg'.  Two colons mean an option that
-   wants an optional arg; if there is text in the current ARGV-element,
-   it is returned in `optarg', otherwise `optarg' is set to zero.
-
-   If OPTSTRING starts with `-' or `+', it requests different methods of
-   handling the non-option ARGV-elements.
-   See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
-
-   Long-named options begin with `--' instead of `-'.
-   Their names may be abbreviated as long as the abbreviation is unique
-   or is an exact match for some defined option.  If they have an
-   argument, it follows the option name in the same ARGV-element, separated
-   from the option name by a `=', or else the in next ARGV-element.
-   When `getopt' finds a long-named option, it returns 0 if that option's
-   `flag' field is nonzero, the value of the option's `val' field
-   if the `flag' field is zero.
-
-   The elements of ARGV aren't really const, because we permute them.
-   But we pretend they're const in the prototype to be compatible
-   with other systems.
-
-   LONGOPTS is a vector of `struct option' terminated by an
-   element containing a name which is zero.
-
-   LONGIND returns the index in LONGOPT of the long-named option found.
-   It is only valid when a long-named option has been found by the most
-   recent call.
-
-   If LONG_ONLY is nonzero, '-' as well as '--' can introduce
-   long-named options.  */
-
 int
-_getopt_internal (
-     int argc,
-     char *const *argv,
-     const char *optstring,
-     const struct option *longopts,
-     int *longind,
-     int long_only);
-int
-_getopt_internal (
-     int argc,
-     char *const *argv,
-     const char *optstring,
-     const struct option *longopts,
-     int *longind,
-     int long_only)
+SOX_API lsx_getopt(
+    LSX_PARAM_INOUT lsx_getopt_t * state)
 {
-  int print_errors = opterr;
-  if (optstring[0] == ':')
-    print_errors = 0;
-
-  if (argc < 1)
-    return -1;
-
-  lsx_optarg = NULL;
-
-  if (lsx_optind == 0 || !__getopt_initialized)
+    int oerr;
+    assert(state);
+    if (!state)
     {
-      if (lsx_optind == 0)
-        lsx_optind = 1;     /* Don't scan ARGV[0], the program name.  */
-      optstring = _getopt_initialize (argc, argv, optstring);
-      __getopt_initialized = 1;
+        lsx_fail("lsx_getopt called with state=NULL");
+        return -1;
     }
 
-  /* Test whether ARGV[optind] points to a non-option argument.
-     Either it does not have option syntax, or there is an environment flag
-     from the shell indicating it is not an option.  The later information
-     is only used when the used in the GNU libc.  */
-#if defined _LIBC && defined USE_NONOPTION_FLAGS
-# define NONOPTION_P (argv[lsx_optind][0] != '-' || argv[lsx_optind][1] == '\0'       \
-                      || (lsx_optind < nonoption_flags_len                        \
-                          && __getopt_nonoption_flags[lsx_optind] == '1'))
-#else
-# define NONOPTION_P (argv[lsx_optind][0] != '-' || argv[lsx_optind][1] == '\0')
-#endif
+    assert(state->argc >= 0);
+    assert(state->argv != NULL);
+    assert(state->shortopts);
+    assert(state->ind >= 0);
+    assert(state->ind <= state->argc + 1);
 
-  if (nextchar == NULL || *nextchar == '\0')
-    {
-      /* Advance to the next ARGV-element.  */
+    oerr = 0 != (state->flags & lsx_getopt_flag_opterr);
+    state->opt = 0;
+    state->arg = NULL;
+    state->lngind = -1;
 
-      /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
-         moved back by the user (who may also have changed the arguments).  */
-      if (last_nonopt > lsx_optind)
-        last_nonopt = lsx_optind;
-      if (first_nonopt > lsx_optind)
-        first_nonopt = lsx_optind;
-
-      if (ordering == PERMUTE)
-        {
-          /* If we have just processed some options following some non-options,
-             exchange them so that the options come first.  */
-
-          if (first_nonopt != last_nonopt && last_nonopt != lsx_optind)
-            exchange ((char **) argv);
-          else if (last_nonopt != lsx_optind)
-            first_nonopt = lsx_optind;
-
-          /* Skip any additional non-options
-             and extend the range of non-options previously skipped.  */
-
-          while (lsx_optind < argc && NONOPTION_P)
-            lsx_optind++;
-          last_nonopt = lsx_optind;
-        }
-
-      /* The special ARGV-element `--' means premature end of options.
-         Skip it like a null option,
-         then exchange with previous non-options as if it were an option,
-         then skip everything else like a non-option.  */
-
-      if (lsx_optind != argc && !strcmp (argv[lsx_optind], "--"))
-        {
-          lsx_optind++;
-
-          if (first_nonopt != last_nonopt && last_nonopt != lsx_optind)
-            exchange ((char **) argv);
-          else if (first_nonopt == last_nonopt)
-            first_nonopt = lsx_optind;
-          last_nonopt = argc;
-
-          lsx_optind = argc;
-        }
-
-      /* If we have done all the ARGV-elements, stop the scan
-         and back over any non-options that we skipped and permuted.  */
-
-      if (lsx_optind == argc)
-        {
-          /* Set the next-arg-index to point at the non-options
-             that we previously skipped, so the caller will digest them.  */
-          if (first_nonopt != last_nonopt)
-            lsx_optind = first_nonopt;
-          nextchar = NULL;  /* SoX */
-          return -1;
-        }
-
-      /* If we have come to a non-option and did not permute it,
-         either stop the scan or describe it to the caller and pass it by.  */
-
-      if (NONOPTION_P)
-        {
-          if (ordering == REQUIRE_ORDER)
-            return -1;
-          lsx_optarg = argv[lsx_optind++];
-          return 1;
-        }
-
-      /* We have found another option-ARGV-element.
-         Skip the initial punctuation.  */
-
-      nextchar = (argv[lsx_optind] + 1
-                  + (longopts != NULL && argv[lsx_optind][1] == '-'));
+    if (state->argc < 0 ||
+        !state->argv ||
+        !state->shortopts ||
+        state->ind < 0)
+    { /* programmer error */
+        lsx_fail("lsx_getopt called with invalid information");
+        state->curpos = NULL;
+        return -1;
     }
+    else if (
+        state->argc <= state->ind ||
+        !state->argv[state->ind] ||
+        state->argv[state->ind][0] != '-' ||
+        state->argv[state->ind][1] == '\0')
+    { /* return no more options */
+        state->curpos = NULL;
+        return -1;
+    }
+    else if (state->argv[state->ind][1] == '-' && state->argv[state->ind][2] == '\0')
+    { /* skip "--", return no more options. */
+        state->curpos = NULL;
+        state->ind++;
+        return -1;
+    }
+    else
+    { /* Look for the next option */
+        char const * current = state->argv[state->ind];
+        char const * param = current + 1;
 
-  /* Decode the current option-ARGV-element.  */
+        if (state->curpos == NULL ||
+            state->curpos <= param ||
+            param + strlen(param) <= state->curpos)
+        { /* Start parsing a new parameter - check for a long option */
+            state->curpos = NULL;
 
-  /* Check whether the ARGV-element is a long option.
+            if (state->longopts &&
+                (param[0] == '-' || (state->flags & lsx_getopt_flag_longonly)))
+            {
+                size_t nameLen;
+                int doubleDash = param[0] == '-';
+                if (doubleDash)
+                {
+                    param++;
+                }
 
-     If long_only and the ARGV-element has the form "-f", where f is
-     a valid short option, don't consider it an abbreviated form of
-     a long option that starts with f.  Otherwise there would be no
-     way to give the -f short option.
+                for (nameLen = 0; param[nameLen] && param[nameLen] != '='; nameLen++)
+                {}
 
-     On the other hand, if there's a long option "fubar" and
-     the ARGV-element is "-fu", do consider that an abbreviation of
-     the long option, just like "--fu", and not "-f" with arg "u".
+                /* For single-dash, you have to specify at least two letters in the name. */
+                if (doubleDash || nameLen >= 2)
+                {
+                    lsx_option_t const * pCur;
+                    lsx_option_t const * pMatch = NULL;
+                    int matches = 0;
 
-     This distinction seems to be the most useful approach.  */
-
-  if (longopts != NULL
-      && (argv[lsx_optind][1] == '-'
-          || (long_only && (argv[lsx_optind][2] || !my_index (optstring, argv[lsx_optind][1])))))
-    {
-      char *nameend;
-      const struct option *p;
-      const struct option *pfound = NULL;
-      int exact = 0;
-      int ambig = 0;
-      int indfound = -1;
-      int option_index;
-
-      for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
-        /* Do nothing.  */ ;
-
-      /* Test all long options for either exact match
-         or abbreviated matches.  */
-      for (p = longopts, option_index = 0; p->name; p++, option_index++)
-        if (!strncmp (p->name, nextchar, (size_t)(nameend - nextchar)))
-          {
-            if ((unsigned int) (nameend - nextchar)
-                == (unsigned int) strlen (p->name))
-              {
-                /* Exact match found.  */
-                pfound = p;
-                indfound = option_index;
-                exact = 1;
-                break;
-              }
-            else if (pfound == NULL)
-              {
-                /* First nonexact match found.  */
-                pfound = p;
-                indfound = option_index;
-              }
-            else if (long_only
-                     || pfound->has_arg != p->has_arg
-                     || pfound->flag != p->flag
-                     || pfound->val != p->val)
-              /* Second or later nonexact match found.  */
-              ambig = 1;
-          }
+                    for (pCur = state->longopts; pCur->name; pCur++)
+                    {
+                        if (0 == strncmp(pCur->name, param, nameLen))
+                        { /* Prefix match. */
+                            matches++;
+                            pMatch = pCur;
+                            if (nameLen == strlen(pCur->name))
+                            { /* Exact match - no ambiguity, stop search. */
+                                matches = 1;
+                                break;
+                            }
+                        }
+                    }
 
-      if (ambig && !exact)
-        {
-          if (print_errors)
-            {
-#if defined _LIBC && defined USE_IN_LIBIO
-              char *buf;
+                    if (matches == 1)
+                    { /* Matched. */
+                        state->ind++;
 
-              if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
-                              argv[0], argv[lsx_optind]) >= 0)
-                {
-
-                  if (_IO_fwide (stderr, 0) > 0)
-                    __fwprintf (stderr, L"%s", buf);
-                  else
-                    fputs (buf, stderr);
-
-                  free (buf);
-                }
-#else
-              fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
-                       argv[0], argv[lsx_optind]);
-#endif
-            }
-          nextchar += strlen (nextchar);
-          lsx_optind++;
-          optopt = 0;
-          return '?';
-        }
-
-      if (pfound != NULL)
-        {
-          option_index = indfound;
-          lsx_optind++;
-          if (*nameend)
-            {
-              /* Don't test has_arg with >, because some C compilers don't
-                 allow it to be used on enums.  */
-              if (pfound->has_arg)
-                lsx_optarg = nameend + 1;
-              else
-                {
-                  if (print_errors)
-                    {
-#if defined _LIBC && defined USE_IN_LIBIO
-                      char *buf;
-                      int n;
-#endif
+                        if (param[nameLen])
+                        { /* --name=value */
+                            if (pMatch->has_arg)
+                            { /* Required or optional arg - done. */
+                                state->arg = param + nameLen + 1;
+                            }
+                            else
+                            { /* No arg expected. */
+                                if (oerr)
+                                {
+                                    lsx_warn("`%s' did not expect an argument from `%s'",
+                                        pMatch->name,
+                                        current);
+                                }
+                                return '?';
+                            }
+                        }
+                        else if (pMatch->has_arg == lsx_option_arg_required)
+                        { /* Arg required. */
+                            state->arg = state->argv[state->ind];
+                            state->ind++;
+                            if (state->ind > state->argc)
+                            {
+                                if (oerr)
+                                {
+                                    lsx_warn("`%s' requires an argument from `%s'",
+                                        pMatch->name,
+                                        current);
+                                }
+                                return state->shortopts[0] == ':' ? ':' : '?'; /* Missing required value. */
+                            }
+                        }
 
-                      if (argv[lsx_optind - 1][1] == '-')
+                        state->lngind = pMatch - state->longopts;
+                        if (pMatch->flag)
                         {
-                          /* --option */
-#if defined _LIBC && defined USE_IN_LIBIO
-                          n = __asprintf (&buf, _("\
-%s: option `--%s' doesn't allow an argument\n"),
-                                          argv[0], pfound->name);
-#else
-                          fprintf (stderr, _("\
-%s: option `--%s' doesn't allow an argument\n"),
-                                   argv[0], pfound->name);
-#endif
+                            *pMatch->flag = pMatch->val;
+                            return 0;
                         }
-                      else
+                        else
                         {
-                          /* +option or -option */
-#if defined _LIBC && defined USE_IN_LIBIO
-                          n = __asprintf (&buf, _("\
-%s: option `%c%s' doesn't allow an argument\n"),
-                                          argv[0], argv[lsx_optind - 1][0],
-                                          pfound->name);
-#else
-                          fprintf (stderr, _("\
-%s: option `%c%s' doesn't allow an argument\n"),
-                                   argv[0], argv[lsx_optind - 1][0], pfound->name);
-#endif
+                            return pMatch->val;
                         }
-
-#if defined _LIBC && defined USE_IN_LIBIO
-                      if (n >= 0)
+                    }
+                    else if (matches == 0 && doubleDash)
+                    { /* No match */
+                        if (oerr)
                         {
-                          if (_IO_fwide (stderr, 0) > 0)
-                            __fwprintf (stderr, L"%s", buf);
-                          else
-                            fputs (buf, stderr);
-
-                          free (buf);
+                            lsx_warn("parameter not recognized from `%s'", current);
                         }
-#endif
+                        state->ind++;
+                        return '?';
                     }
-
-                  nextchar += strlen (nextchar);
-
-                  optopt = pfound->val;
-                  return '?';
-                }
-            }
-          else if (pfound->has_arg == 1)
-            {
-              if (lsx_optind < argc)
-                lsx_optarg = argv[lsx_optind++];
-              else
-                {
-                  if (print_errors)
-                    {
-#if defined _LIBC && defined USE_IN_LIBIO
-                      char *buf;
-
-                      if (__asprintf (&buf, _("\
-%s: option `%s' requires an argument\n"),
-                                      argv[0], argv[lsx_optind - 1]) >= 0)
-                        {
-                          if (_IO_fwide (stderr, 0) > 0)
-                            __fwprintf (stderr, L"%s", buf);
-                          else
-                            fputs (buf, stderr);
-
-                          free (buf);
+                    else if (matches > 1)
+                    { /* Ambiguous. */
+                        if (oerr)
+                        {
+                            lsx_warn("parameter `%s' is ambiguous:", current);
+                            for (pCur = state->longopts; pCur->name; pCur++)
+                            {
+                                if (0 == strncmp(pCur->name, param, nameLen))
+                                {
+                                    lsx_warn("parameter `%s' could be `--%s'", current, pCur->name);
+                                }
+                            }
                         }
-#else
-                      fprintf (stderr,
-                               _("%s: option `%s' requires an argument\n"),
-                               argv[0], argv[lsx_optind - 1]);
-#endif
+                        state->ind++;
+                        return '?';
                     }
-                  nextchar += strlen (nextchar);
-                  optopt = pfound->val;
-                  return optstring[0] == ':' ? ':' : '?';
                 }
             }
-          nextchar += strlen (nextchar);
-          if (longind != NULL)
-            *longind = option_index;
-          if (pfound->flag)
-            {
-              *(pfound->flag) = pfound->val;
-              return 0;
-            }
-          return pfound->val;
+
+            state->curpos = param;
         }
 
-      /* Can't find it as a long option.  If this is not getopt_long_only,
-         or the option starts with '--' or is not a valid short
-         option, then it's an error.
-         Otherwise interpret it as a short option.  */
-      if (!long_only || argv[lsx_optind][1] == '-'
-          || my_index (optstring, *nextchar) == NULL)
-        {
-          if (print_errors)
+        state->opt = state->curpos[0];
+        if (state->opt == ':')
+        { /* ':' is never a valid short option character */
+            if (oerr)
             {
-#if defined _LIBC && defined USE_IN_LIBIO
-              char *buf;
-              int n;
-#endif
-
-              if (argv[lsx_optind][1] == '-')
-                {
-                  /* --option */
-#if defined _LIBC && defined USE_IN_LIBIO
-                  n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
-                                  argv[0], nextchar);
-#else
-                  fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
-                           argv[0], nextchar);
-#endif
-                }
-              else
-                {
-                  /* +option or -option */
-#if defined _LIBC && defined USE_IN_LIBIO
-                  n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
-                                  argv[0], argv[lsx_optind][0], nextchar);
-#else
-                  fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
-                           argv[0], argv[lsx_optind][0], nextchar);
-#endif
-                }
-
-#if defined _LIBC && defined USE_IN_LIBIO
-              if (n >= 0)
-                {
-                  if (_IO_fwide (stderr, 0) > 0)
-                    __fwprintf (stderr, L"%s", buf);
-                  else
-                    fputs (buf, stderr);
-
-                  free (buf);
-                }
-#endif
+                lsx_warn("option `%c' not recognized", state->opt);
             }
-          nextchar = (char *) "";
-          lsx_optind++;
-          optopt = 0;
-          return '?';
+            state->curpos++;
+            CheckCurPosEnd(state);
+            return '?'; /* unrecognized option */
         }
-    }
-
-  /* Look at and handle the next short option-character.  */
-
-  {
-    char c = *nextchar++;
-    char *temp = my_index (optstring, c);
-
-    /* Increment `optind' when we start to process its last character.  */
-    if (temp && *nextchar == '\0') /* SoX */
-      ++lsx_optind;
-
-    if (temp == NULL || c == ':')
-      {
-        if (print_errors)
-          {
-#if defined _LIBC && defined USE_IN_LIBIO
-              char *buf;
-              int n;
-#endif
-
-            if (posixly_correct)
-              {
-                /* 1003.2 specifies the format of this message.  */
-#if defined _LIBC && defined USE_IN_LIBIO
-                n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
-                                argv[0], c);
-#else
-                fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
-#endif
-              }
-            else
-              {
-#if defined _LIBC && defined USE_IN_LIBIO
-                n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
-                                argv[0], c);
-#else
-                fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
-#endif
-              }
-
-#if defined _LIBC && defined USE_IN_LIBIO
-            if (n >= 0)
-              {
-                if (_IO_fwide (stderr, 0) > 0)
-                  __fwprintf (stderr, L"%s", buf);
-                else
-                  fputs (buf, stderr);
-
-                free (buf);
-              }
-#endif
-          }
-        nextchar = (char *) "";  /* SoX */
-        optopt = c;
-        return '?';
-      }
-    /* Convenience. Treat POSIX -W foo same as long option --foo */
-    if (temp[0] == 'W' && temp[1] == ';')
-      {
-        char *nameend;
-        const struct option *p;
-        const struct option *pfound = NULL;
-        int exact = 0;
-        int ambig = 0;
-        int indfound = 0;
-        int option_index;
-
-        /* This is an option that requires an argument.  */
-        if (*nextchar != '\0')
-          {
-            lsx_optarg = nextchar;
-            /* If we end this ARGV-element by taking the rest as an arg,
-               we must advance to the next element now.  */
-            lsx_optind++;
-          }
-        else if (lsx_optind == argc)
-          {
-            if (print_errors)
-              {
-                /* 1003.2 specifies the format of this message.  */
-#if defined _LIBC && defined USE_IN_LIBIO
-                char *buf;
-
-                if (__asprintf (&buf,
-                                _("%s: option requires an argument -- %c\n"),
-                                argv[0], c) >= 0)
-                  {
-                    if (_IO_fwide (stderr, 0) > 0)
-                      __fwprintf (stderr, L"%s", buf);
-                    else
-                      fputs (buf, stderr);
-
-                    free (buf);
-                  }
-#else
-                fprintf (stderr, _("%s: option requires an argument -- %c\n"),
-                         argv[0], c);
-#endif
-              }
-            optopt = c;
-            if (optstring[0] == ':')
-              c = ':';
-            else
-              c = '?';
-            return c;
-          }
         else
-          /* We already incremented `optind' once;
-             increment it again when taking next ARGV-elt as argument.  */
-          lsx_optarg = argv[lsx_optind++];
+        { /* Short option needs to be matched from option list */
+            char const * pShortopt = strchr(state->shortopts, state->opt);
+            state->curpos++;
 
-        /* optarg is now the argument, see if it's in the
-           table of longopts.  */
-
-        for (nextchar = nameend = lsx_optarg; *nameend && *nameend != '='; nameend++)
-          /* Do nothing.  */ ;
-
-        /* Test all long options for either exact match
-           or abbreviated matches.  */
-        for (p = longopts, option_index = 0; p->name; p++, option_index++)
-          if (!strncmp (p->name, nextchar, (size_t)(nameend - nextchar)))
-            {
-              if ((unsigned int) (nameend - nextchar) == strlen (p->name))
+            if (!pShortopt)
+            { /* unrecognized option */
+                if (oerr)
                 {
-                  /* Exact match found.  */
-                  pfound = p;
-                  indfound = option_index;
-                  exact = 1;
-                  break;
+                    lsx_warn("option `%c' not recognized", state->opt);
                 }
-              else if (pfound == NULL)
-                {
-                  /* First nonexact match found.  */
-                  pfound = p;
-                  indfound = option_index;
-                }
-              else
-                /* Second or later nonexact match found.  */
-                ambig = 1;
+                CheckCurPosEnd(state);
+                return '?';
             }
-        if (ambig && !exact)
-          {
-            if (print_errors)
-              {
-#if defined _LIBC && defined USE_IN_LIBIO
-                char *buf;
-
-                if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
-                                argv[0], argv[lsx_optind]) >= 0)
-                  {
-                    if (_IO_fwide (stderr, 0) > 0)
-                      __fwprintf (stderr, L"%s", buf);
-                    else
-                      fputs (buf, stderr);
-
-                    free (buf);
-                  }
-#else
-                fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
-                         argv[0], argv[lsx_optind]);
-#endif
-              }
-            nextchar += strlen (nextchar);
-            lsx_optind++;
-            return '?';
-          }
-        if (pfound != NULL)
-          {
-            option_index = indfound;
-            if (*nameend)
-              {
-                /* Don't test has_arg with >, because some C compilers don't
-                   allow it to be used on enums.  */
-                if (pfound->has_arg)
-                  lsx_optarg = nameend + 1;
+            else if (pShortopt[1] == ':' && state->curpos[0])
+            { /* Return the rest of the parameter as the option's value */
+                state->arg = state->curpos;
+                state->curpos = NULL;
+                state->ind++;
+                return state->opt;
+            }
+            else if (pShortopt[1] == ':' && pShortopt[2] != ':')
+            { /* Option requires a value */
+                state->curpos = NULL;
+                state->ind++;
+                state->arg = state->argv[state->ind];
+                state->ind++;
+                if (state->ind <= state->argc)
+                { /* A value was present, so we're good. */
+                    return state->opt;
+                }
                 else
-                  {
-                    if (print_errors)
-                      {
-#if defined _LIBC && defined USE_IN_LIBIO
-                        char *buf;
-
-                        if (__asprintf (&buf, _("\
-%s: option `-W %s' doesn't allow an argument\n"),
-                                        argv[0], pfound->name) >= 0)
-                          {
-                            if (_IO_fwide (stderr, 0) > 0)
-                              __fwprintf (stderr, L"%s", buf);
-                            else
-                              fputs (buf, stderr);
-
-                            free (buf);
-                          }
-#else
-                        fprintf (stderr, _("\
-%s: option `-W %s' doesn't allow an argument\n"),
-                                 argv[0], pfound->name);
-#endif
-                      }
-
-                    nextchar += strlen (nextchar);
-                    return '?';
-                  }
-              }
-            else if (pfound->has_arg == 1)
-              {
-                if (lsx_optind < argc)
-                  lsx_optarg = argv[lsx_optind++];
-                else
-                  {
-                    if (print_errors)
-                      {
-#if defined _LIBC && defined USE_IN_LIBIO
-                        char *buf;
-
-                        if (__asprintf (&buf, _("\
-%s: option `%s' requires an argument\n"),
-                                        argv[0], argv[lsx_optind - 1]) >= 0)
-                          {
-                            if (_IO_fwide (stderr, 0) > 0)
-                              __fwprintf (stderr, L"%s", buf);
-                            else
-                              fputs (buf, stderr);
-
-                            free (buf);
-                          }
-#else
-                        fprintf (stderr,
-                                 _("%s: option `%s' requires an argument\n"),
-                                 argv[0], argv[lsx_optind - 1]);
-#endif
-                      }
-                    nextchar += strlen (nextchar);
-                    return optstring[0] == ':' ? ':' : '?';
-                  }
-              }
-            nextchar += strlen (nextchar);
-            if (longind != NULL)
-              *longind = option_index;
-            if (pfound->flag)
-              {
-                *(pfound->flag) = pfound->val;
-                return 0;
-              }
-            return pfound->val;
-          }
-          nextchar = NULL;
-          return 'W';   /* Let the application handle it.   */
-      }
-    if (temp[1] == ':')
-      {
-        if (temp[2] == ':')
-          {
-            /* This is an option that accepts an argument optionally.  */
-            if (*nextchar != '\0')
-              {
-                lsx_optarg = nextchar;
-                lsx_optind++;
-              }
-            else
-              lsx_optarg = NULL;
-            nextchar = NULL;
-          }
-        else
-          {
-            /* This is an option that requires an argument.  */
-            if (*nextchar != '\0')
-              {
-                lsx_optarg = nextchar;
-                /* If we end this ARGV-element by taking the rest as an arg,
-                   we must advance to the next element now.  */
-                lsx_optind++;
-              }
-            else if (lsx_optind == argc)
-              {
-                if (print_errors)
-                  {
-                    /* 1003.2 specifies the format of this message.  */
-#if defined _LIBC && defined USE_IN_LIBIO
-                    char *buf;
-
-                    if (__asprintf (&buf, _("\
-%s: option requires an argument -- %c\n"),
-                                    argv[0], c) >= 0)
-                      {
-                        if (_IO_fwide (stderr, 0) > 0)
-                          __fwprintf (stderr, L"%s", buf);
-                        else
-                          fputs (buf, stderr);
-
-                        free (buf);
-                      }
-#else
-                    fprintf (stderr,
-                             _("%s: option requires an argument -- %c\n"),
-                             argv[0], c);
-#endif
-                  }
-                optopt = c;
-                if (optstring[0] == ':')
-                  c = ':';
-                else
-                  c = '?';
-              }
-            else
-              /* We already incremented `optind' once;
-                 increment it again when taking next ARGV-elt as argument.  */
-              lsx_optarg = argv[lsx_optind++];
-            nextchar = NULL;
-          }
-      }
-    return c;
-  }
+                {  /* Missing required value. */
+                    if (oerr)
+                    {
+                        lsx_warn("option `%c' requires an argument",
+                            state->opt);
+                    }
+                    return state->shortopts[0] == ':' ? ':' : '?';
+                }
+            }
+            else
+            { /* Option without a value. */
+                CheckCurPosEnd(state);
+                return state->opt;
+            }
+        }
+    }
 }
 
-int
-lsx_getopt (int argc, char * const * argv, char const * optstring)
-{
-  return _getopt_internal (argc, argv, optstring,
-                           (const struct option *) 0,
-                           (int *) 0,
-                           0);
-}
+#ifdef TEST_GETOPT
 
-#endif  /* Not ELIDE_CODE.  */
-
-#ifdef TEST
+#include <stdio.h>
 
-/* Compile with -DTEST to make an executable for use in testing
-   the above definition of `getopt'.  */
-
-int
-main (argc, argv)
-     int argc;
-     char **argv;
+int main(int argc, char const * argv[])
 {
-  int c;
-  int digit_optind = 0;
-
-  while (1)
+    static int help = 0;
+    static lsx_option_t longopts[] =
     {
-      int this_option_optind = lsx_optind ? lsx_optind : 1;
+        {"a11",  0, 0, 101},
+        {"a12",  0, 0, 102},
+        {"a122", 0, 0, 103},
+        {"rarg", 1, 0, 104},
+        {"oarg", 2, 0, 105},
+        {"help", 0, &help, 106},
+        {0}
+    };
 
-      c = getopt (argc, argv, "abc:d:0123456789");
-      if (c == -1)
-        break;
+    int ch;
+    lsx_getopt_t state;
+    lsx_getopt_init(argc, argv, "abc:d:v::0123456789", longopts, sox_true, 1, &state);
 
-      switch (c)
-        {
-        case '0':
-        case '1':
-        case '2':
-        case '3':
-        case '4':
-        case '5':
-        case '6':
-        case '7':
-        case '8':
-        case '9':
-          if (digit_optind != 0 && digit_optind != this_option_optind)
-            printf ("digits occur in two different argv-elements.\n");
-          digit_optind = this_option_optind;
-          printf ("option %c\n", c);
-          break;
-
-        case 'a':
-          printf ("option a\n");
-          break;
-
-        case 'b':
-          printf ("option b\n");
-          break;
-
-        case 'c':
-          printf ("option c with value `%s'\n", lsx_optarg);
-          break;
-
-        case '?':
-          break;
-
-        default:
-          printf ("?? getopt returned character code 0%o ??\n", c);
-        }
-    }
-
-  if (lsx_optind < argc)
+    while (-1 != (ch = lsx_getopt(&state)))
     {
-      printf ("non-option ARGV-elements: ");
-      while (lsx_optind < argc)
-        printf ("%s ", argv[lsx_optind++]);
-      printf ("\n");
+        printf(
+            "H=%d ch=%d, ind=%d opt=%d lng=%d arg=%s\n",
+            help,
+            ch,
+            state.ind,
+            state.opt,
+            state.lngind,
+            state.arg ? state.arg : "NULL");
     }
 
-  exit (0);
+    return 0;
 }
 
-#endif /* TEST */
+#endif /* TEST_GETOPT */
--- a/src/getopt1.c
+++ /dev/null
@@ -1,221 +1,0 @@
-#include "soxconfig.h"
-/* getopt_long and getopt_long_only entry points for GNU getopt.
-   Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98
-     Free Software Foundation, Inc.
-   This file is part of the GNU C Library.
-
- * This library is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 2.1 of the License, or (at
- * your option) any later version.
- *
- * This library is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
- * General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this library; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- */
-
-#if 0
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-#endif
-
-#if 0
-#ifdef _LIBC
-# include <getopt.h>
-#else
-# include "getopt.h"
-#endif
-#endif
-#include "sgetopt.h"
-
-#if !defined __STDC__ || !__STDC__
-/* This is a separate conditional since some stdc systems
-   reject `defined (const)'.  */
-#ifndef const
-#define const
-#endif
-#endif
-
-#include <stdio.h>
-
-/* Comment out all this code if we are using the GNU C Library, and are not
-   actually compiling the library itself.  This code is part of the GNU C
-   Library, but also included in many other GNU distributions.  Compiling
-   and linking in this code is a waste when using the GNU C library
-   (especially if it is a shared library).  Rather than having every GNU
-   program understand `configure --with-gnu-libc' and omit the object files,
-   it is simpler to just do this in the source for each such file.  */
-
-#define GETOPT_INTERFACE_VERSION 2
-#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
-#include <gnu-versions.h>
-#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
-#define ELIDE_CODE
-#endif
-#endif
-
-/* Always compile for SoX. */
-#undef ELIDE_CODE
-
-#ifndef ELIDE_CODE
-
-
-/* This needs to come after some library #include
-   to get __GNU_LIBRARY__ defined.  */
-#ifdef __GNU_LIBRARY__
-#include <stdlib.h>
-#endif
-
-#ifndef NULL
-#define NULL 0
-#endif
-
-
-int
-lsx_getopt_long (
-     int argc,
-     char *const *argv,
-     const char *options,
-     const struct option *long_options,
-     int *opt_index);
-int
-lsx_getopt_long (
-     int argc,
-     char *const *argv,
-     const char *options,
-     const struct option *long_options,
-     int *opt_index)
-{
-  return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
-}
-
-/* Like getopt_long, but '-' as well as '--' can indicate a long option.
-   If an option that starts with '-' (not '--') doesn't match a long option,
-   but does match a short option, it is parsed as a short option
-   instead.  */
-
-int
-getopt_long_only (
-     int argc,
-     char *const *argv,
-     const char *options,
-     const struct option *long_options,
-     int *opt_index);
-int
-getopt_long_only (
-     int argc,
-     char *const *argv,
-     const char *options,
-     const struct option *long_options,
-     int *opt_index)
-{
-  return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
-}
-
-# ifdef _LIBC
-libc_hidden_def (lsx_getopt_long)
-libc_hidden_def (getopt_long_only)
-# endif
-
-#endif  /* Not ELIDE_CODE.  */
-
-#ifdef TEST
-
-#include <stdio.h>
-
-
-int
-main (argc, argv)
-     int argc;
-     char **argv;
-{
-  int c;
-  int digit_optind = 0;
-
-  while (1)
-    {
-      int this_option_optind = optind ? optind : 1;
-      int option_index = 0;
-      static struct option long_options[] =
-      {
-        {"add", 1, 0, 0},
-        {"append", 0, 0, 0},
-        {"delete", 1, 0, 0},
-        {"verbose", 0, 0, 0},
-        {"create", 0, 0, 0},
-        {"file", 1, 0, 0},
-        {0, 0, 0, 0}
-      };
-
-      c = lsx_getopt_long (argc, argv, "abc:d:0123456789",
-                       long_options, &option_index);
-      if (c == -1)
-        break;
-
-      switch (c)
-        {
-        case 0:
-          printf ("option %s", long_options[option_index].name);
-          if (optarg)
-            printf (" with arg %s", optarg);
-          printf ("\n");
-          break;
-
-        case '0':
-        case '1':
-        case '2':
-        case '3':
-        case '4':
-        case '5':
-        case '6':
-        case '7':
-        case '8':
-        case '9':
-          if (digit_optind != 0 && digit_optind != this_option_optind)
-            printf ("digits occur in two different argv-elements.\n");
-          digit_optind = this_option_optind;
-          printf ("option %c\n", c);
-          break;
-
-        case 'a':
-          printf ("option a\n");
-          break;
-
-        case 'b':
-          printf ("option b\n");
-          break;
-
-        case 'c':
-          printf ("option c with value `%s'\n", optarg);
-          break;
-
-        case 'd':
-          printf ("option d with value `%s'\n", optarg);
-          break;
-
-        case '?':
-          break;
-
-        default:
-          printf ("?? getopt returned character code 0%o ??\n", c);
-        }
-    }
-
-  if (optind < argc)
-    {
-      printf ("non-option ARGV-elements: ");
-      while (optind < argc)
-        printf ("%s ", argv[optind++]);
-      printf ("\n");
-    }
-
-  exit (0);
-}
-
-#endif /* TEST */
--- a/src/rate.c
+++ b/src/rate.c
@@ -25,7 +25,6 @@
 
 #include "sox_i.h"
 #include "fft4g.h"
-#include "sgetopt.h"
 #include "dft_filter.h"
 #include <assert.h>
 #include <string.h>
@@ -440,15 +439,17 @@
   priv_t * p = (priv_t *) effp->priv;
   int c;
   char * dummy_p, * found_at, * opts = "+i:b:p:MILasqlmhv", * qopts = opts +12;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, opts, NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->quality = -1;
   p->phase = 50;
   p->shared_ptr = &p->shared;
 
-  while ((c = lsx_getopt(argc, argv, opts)) != -1) switch (c) {
-    GETOPT_NUMERIC('i', coef_interp, 1 , 3)
-    GETOPT_NUMERIC('p', phase,  0 , 100)
-    GETOPT_NUMERIC('b', bandwidth,  100 - LSX_MAX_TBW3, 99.7)
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
+    GETOPT_NUMERIC(optstate, 'i', coef_interp, 1 , 3)
+    GETOPT_NUMERIC(optstate, 'p', phase,  0 , 100)
+    GETOPT_NUMERIC(optstate, 'b', bandwidth,  100 - LSX_MAX_TBW3, 99.7)
     case 'M': p->phase =  0; break;
     case 'I': p->phase = 25; break;
     case 'L': p->phase = 50; break;
@@ -455,9 +456,9 @@
     case 's': p->bandwidth = 99; break;
     case 'a': p->allow_aliasing = sox_true; break;
     default: if ((found_at = strchr(qopts, c))) p->quality = found_at - qopts;
-      else {lsx_fail("unknown option `-%c'", optopt); return lsx_usage(effp);}
+      else {lsx_fail("unknown option `-%c'", optstate.opt); return lsx_usage(effp);}
   }
-  argc -= lsx_optind, argv += lsx_optind;
+  argc -= optstate.ind, argv += optstate.ind;
 
   if ((unsigned)p->quality < 2 && (p->bandwidth || p->phase != 50 || p->allow_aliasing)) {
     lsx_fail("override options not allowed with this quality level");
--- a/src/sgetopt.h
+++ /dev/null
@@ -1,188 +1,0 @@
-/* Declarations for getopt.
-   Copyright (C) 1989-1994, 1996-1999, 2001 Free Software Foundation, Inc.
-   This file is part of the GNU C Library.
-
- * This library is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 2.1 of the License, or (at
- * your option) any later version.
- *
- * This library is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
- * General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this library; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
- */
-
-#ifndef _SGETOPT_H
-#if defined __GNUC__
-  #pragma GCC system_header
-#elif defined __SUNPRO_CC
-  #pragma disable_warn
-#elif defined _MSC_VER
-  #pragma warning(push, 1)
-#endif
-
-#ifndef __need_getopt
-# define _GETOPT_H 1
-#endif
-
-/* If __GNU_LIBRARY__ is not already defined, either we are being used
-   standalone, or this is the first header included in the source file.
-   If we are being used with glibc, we need to include <features.h>, but
-   that does not exist if we are standalone.  So: if __GNU_LIBRARY__ is
-   not defined, include <ctype.h>, which will pull in <features.h> for us
-   if it's from glibc.  (Why ctype.h?  It's guaranteed to exist and it
-   doesn't flood the namespace with stuff the way some other headers do.)  */
-#if !defined __GNU_LIBRARY__
-# include <ctype.h>
-#endif
-
-#ifdef  __cplusplus
-extern "C" {
-#endif
-
-/* For communication from `getopt' to the caller.
-   When `getopt' finds an option that takes an argument,
-   the argument value is returned here.
-   Also, when `ordering' is RETURN_IN_ORDER,
-   each non-option ARGV-element is returned here.  */
-
-extern char *lsx_optarg;
-
-/* Index in ARGV of the next element to be scanned.
-   This is used for communication to and from the caller
-   and for communication between successive calls to `getopt'.
-
-   On entry to `getopt', zero means this is the first call; initialize.
-
-   When `getopt' returns -1, this is the index of the first of the
-   non-option elements that the caller should itself scan.
-
-   Otherwise, `optind' communicates from one call to the next
-   how much of ARGV has been scanned so far.  */
-
-extern int lsx_optind;
-
-/* Callers store zero here to inhibit the error message `getopt' prints
-   for unrecognized options.  */
-
-extern int opterr;
-
-/* Set to an option character which was unrecognized.  */
-
-extern int optopt;
-
-#ifndef __need_getopt
-/* Describe the long-named options requested by the application.
-   The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
-   of `struct option' terminated by an element containing a name which is
-   zero.
-
-   The field `has_arg' is:
-   no_argument          (or 0) if the option does not take an argument,
-   required_argument    (or 1) if the option requires an argument,
-   optional_argument    (or 2) if the option takes an optional argument.
-
-   If the field `flag' is not NULL, it points to a variable that is set
-   to the value given in the field `val' when the option is found, but
-   left unchanged if the option is not found.
-
-   To have a long-named option do something other than set an `int' to
-   a compiled-in constant, such as set a value from `optarg', set the
-   option's `flag' field to zero and its `val' field to a nonzero
-   value (the equivalent single-letter option character, if there is
-   one).  For long options that have a zero `flag' field, `getopt'
-   returns the contents of the `val' field.  */
-
-struct option
-{
-# if (defined __STDC__ && __STDC__) || defined __cplusplus
-  const char *name;
-# else
-  char *name;
-# endif
-  /* has_arg can't be an enum because some compilers complain about
-     type mismatches in all the code that assumes it is an int.  */
-  int has_arg;
-  int *flag;
-  int val;
-};
-
-/* Names for the values of the `has_arg' field of `struct option'.  */
-
-# define no_argument            0
-# define required_argument      1
-# define optional_argument      2
-#endif  /* need getopt */
-
-
-/* Get definitions and prototypes for functions to process the
-   arguments in ARGV (ARGC of them, minus the program name) for
-   options given in OPTS.
-
-   Return the option character from OPTS just read.  Return -1 when
-   there are no more options.  For unrecognized options, or options
-   missing arguments, `optopt' is set to the option letter, and '?' is
-   returned.
-
-   The OPTS string is a list of characters which are recognized option
-   letters, optionally followed by colons, specifying that that letter
-   takes an argument, to be placed in `optarg'.
-
-   If a letter in OPTS is followed by two colons, its argument is
-   optional.  This behavior is specific to the GNU `getopt'.
-
-   The argument `--' causes premature termination of argument
-   scanning, explicitly telling `getopt' that there are no more
-   options.
-
-   If OPTS begins with `--', then non-option arguments are treated as
-   arguments to the option '\0'.  This behavior is specific to the GNU
-   `getopt'.  */
-
-#if (defined __STDC__ && __STDC__) || defined __cplusplus
-extern int lsx_getopt (int ___argc, char *const *___argv, const char *__shortopts);
-
-# ifndef __need_getopt
-extern int lsx_getopt_long (int ___argc, char *const *___argv,
-                        const char *__shortopts,
-                        const struct option *__longopts, int *__longind);
-extern int getopt_long_only (int ___argc, char *const *___argv,
-                             const char *__shortopts,
-                             const struct option *__longopts, int *__longind);
-
-/* Internal only.  Users should not call this directly.  */
-extern int _getopt_internal (int ___argc, char *const *___argv,
-                             const char *__shortopts,
-                             const struct option *__longopts, int *__longind,
-                             int __long_only);
-# endif
-#else /* not __STDC__ */
-extern int lsx_getopt ();
-# ifndef __need_getopt
-extern int lsx_getopt_long ();
-extern int getopt_long_only ();
-
-extern int _getopt_internal ();
-# endif
-#endif /* __STDC__ */
-
-#ifdef  __cplusplus
-}
-#endif
-
-/* Make sure we later can get all the definitions and declarations.  */
-#undef __need_getopt
-
-#endif /* getopt.h */
-
-#if defined __SUNPRO_CC
-  #pragma enable_warn
-#elif defined _MSC_VER
-  #pragma warning(pop)
-#endif
-
--- a/src/sinc.c
+++ b/src/sinc.c
@@ -17,7 +17,6 @@
 
 #include "sox_i.h"
 #include "dft_filter.h"
-#include "sgetopt.h"
 #include <string.h>
 
 typedef struct {
@@ -33,6 +32,8 @@
   dft_filter_priv_t * b = &p->base;
   char * parse_ptr = argv[0];
   int i = 0;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, "+ra:b:p:MILt:n:", NULL, lsx_getopt_flag_none, 1, &optstate);
 
   b->filter_ptr = &b->filter;
   p->phase = 50;
@@ -39,17 +40,17 @@
   p->beta = -1;
   while (i < 2) {
     int c = 1;
-    while (c && (c = lsx_getopt(argc, argv, "+ra:b:p:MILt:n:")) != -1) switch (c) {
+    while (c && (c = lsx_getopt(&optstate)) != -1) switch (c) {
       char * parse_ptr2;
       case 'r': p->round = sox_true; break;
-      GETOPT_NUMERIC('a', att,  40 , 180)
-      GETOPT_NUMERIC('b', beta,  0 , 256)
-      GETOPT_NUMERIC('p', phase, 0, 100)
+      GETOPT_NUMERIC(optstate, 'a', att,  40 , 180)
+      GETOPT_NUMERIC(optstate, 'b', beta,  0 , 256)
+      GETOPT_NUMERIC(optstate, 'p', phase, 0, 100)
       case 'M': p->phase =  0; break;
       case 'I': p->phase = 25; break;
       case 'L': p->phase = 50; break;
-      GETOPT_NUMERIC('n', num_taps[1], 11, 32767)
-      case 't': p->tbw1 = lsx_parse_frequency(lsx_optarg, &parse_ptr2);
+      GETOPT_NUMERIC(optstate, 'n', num_taps[1], 11, 32767)
+      case 't': p->tbw1 = lsx_parse_frequency(optstate.arg, &parse_ptr2);
         if (p->tbw1 < 1 || *parse_ptr2) return lsx_usage(effp);
         break;
       default: c = 0;
@@ -58,14 +59,14 @@
       return lsx_usage(effp);
     if (!i || !p->Fc1)
       p->tbw0 = p->tbw1, p->num_taps[0] = p->num_taps[1];
-    if (!i++ && lsx_optind < argc) {
-      if (*(parse_ptr = argv[lsx_optind++]) != '-')
+    if (!i++ && optstate.ind < argc) {
+      if (*(parse_ptr = argv[optstate.ind++]) != '-')
         p->Fc0 = lsx_parse_frequency(parse_ptr, &parse_ptr);
       if (*parse_ptr == '-')
         p->Fc1 = lsx_parse_frequency(parse_ptr + 1, &parse_ptr);
     }
   }
-  return lsx_optind != argc || p->Fc0 < 0 || p->Fc1 < 0 || *parse_ptr ?
+  return optstate.ind != argc || p->Fc0 < 0 || p->Fc1 < 0 || *parse_ptr ?
       lsx_usage(effp) : SOX_SUCCESS;
 }
 
--- a/src/sox.c
+++ b/src/sox.c
@@ -24,7 +24,6 @@
 #include "soxconfig.h"
 #include "sox.h"
 #include "util.h"
-#include "sgetopt.h"
 
 #include <ctype.h>
 #include <errno.h>
@@ -733,7 +732,7 @@
   eff_chain_count = 0;
 } /* delete_eff_chains */
 
-static sox_bool is_pseudo_effect(char *s)
+static sox_bool is_pseudo_effect(const char *s)
 {
   if (s)
   if (strcmp("newfile", s) == 0 ||
@@ -743,9 +742,9 @@
   return sox_false;
 } /* is_pseudo_effect */
 
-static void parse_effects(int argc, char **argv)
+static void parse_effects(int * argi, int argc, char ** argv)
 {
-  while (lsx_optind < argc) {
+  while (*argi < argc) {
     unsigned eff_offset;
     int j;
     int newline_mode = 0;
@@ -757,7 +756,7 @@
     }
 
     /* psuedo-effect ":" is used to create a new effects chain */
-    if (strcmp(argv[lsx_optind], ":") == 0)
+    if (strcmp(argv[*argi], ":") == 0)
     {
       /* Only create a new chain if current one has effects.
        * Error checking will be done when loop is restarted.
@@ -767,15 +766,15 @@
         eff_chain_count++;
         add_eff_chain();
       }
-      lsx_optind++;
+      (*argi)++;
       continue;
     }
 
-    if (strcmp(argv[lsx_optind], "newfile") == 0)
+    if (strcmp(argv[*argi], "newfile") == 0)
     {
       /* Start a new effect chain for newfile if user doesn't
        * manually do it.  Restart loop without advancing
-       * optind to do error checking.
+       * argi to do error checking.
        */
       if (nuser_effects[eff_chain_count] != 0)
       {
@@ -785,11 +784,11 @@
       }
       newline_mode = 1;
     }
-    else if (strcmp(argv[lsx_optind], "restart") == 0)
+    else if (strcmp(argv[*argi], "restart") == 0)
     {
       /* Start a new effect chain for restart if user doesn't
        * manually do it.  Restart loop without advancing
-       * optind to do error checking.
+       * argi to do error checking.
        */
       if (nuser_effects[eff_chain_count] != 0)
       {
@@ -801,13 +800,13 @@
     }
 
     /* Name should always be correct! */
-    user_effargs[eff_chain_count][eff_offset].name = strdup(argv[lsx_optind++]);
-    for (j = 0; j < argc - lsx_optind && !sox_find_effect(argv[lsx_optind + j]) &&
-         !is_pseudo_effect(argv[lsx_optind + j]); ++j)
-      user_effargs[eff_chain_count][eff_offset].argv[j] = strdup(argv[lsx_optind + j]);
+    user_effargs[eff_chain_count][eff_offset].name = strdup(argv[(*argi)++]);
+    for (j = 0; j < argc - *argi && !sox_find_effect(argv[*argi + j]) &&
+         !is_pseudo_effect(argv[*argi + j]); ++j)
+      user_effargs[eff_chain_count][eff_offset].argv[j] = strdup(argv[*argi + j]);
     user_effargs[eff_chain_count][eff_offset].argc = j;
 
-    lsx_optind += j; /* Skip past the effect arguments */
+    *argi += j; /* Skip past the effect arguments */
     nuser_effects[eff_chain_count]++;
     if (newline_mode)
     {
@@ -846,7 +845,7 @@
   return argv;
 }                                /* strtoargv */
 
-static void read_user_effects(char *filename)
+static void read_user_effects(char const *filename)
 {
     FILE *file = fopen(filename, "rt");
     char s[FILENAME_MAX];
@@ -878,6 +877,8 @@
       argv = strtoargv(s, &argc);
 
       if (argv) {
+        int argi;
+
         /* Make sure first option is an effect name. */
         if (!sox_find_effect(argv[0]) && !is_pseudo_effect(argv[0]))
         {
@@ -885,12 +886,8 @@
           exit(1);
         }
 
-        /* parse_effects normally parses options from command line.
-         * Reset opt index so it thinks its back at beginning of
-         * main()'s argv[].
-         */
-        lsx_optind = 0;
-        parse_effects(argc, argv);
+        argi = 0;
+        parse_effects(&argi, argc, argv);
 
         /* Advance to next effect but only if current chain has been
          * filled in.  This recovers from side affects of psuedo-effects.
@@ -2024,50 +2021,50 @@
 static char const * const getoptstr =
   "+ab:c:de:fghimnopqr:st:uv:xABC:DGLMNRSTUV::X12348";
 
-static struct option const long_options[] = {
-  {"add-comment"     , required_argument, NULL, 0},
-  {"buffer"          , required_argument, NULL, 0},
-  {"combine"         , required_argument, NULL, 0},
-  {"comment-file"    , required_argument, NULL, 0},
-  {"comment"         , required_argument, NULL, 0},
-  {"endian"          , required_argument, NULL, 0},
-  {"input-buffer"    , required_argument, NULL, 0},
-  {"interactive"     ,       no_argument, NULL, 0},
-  {"help-effect"     , required_argument, NULL, 0},
-  {"help-format"     , required_argument, NULL, 0},
-  {"no-glob"         ,       no_argument, NULL, 0},
-  {"plot"            , required_argument, NULL, 0},
-  {"replay-gain"     , required_argument, NULL, 0},
-  {"version"         ,       no_argument, NULL, 0},
-  {"output"          , required_argument, NULL, 0},
-  {"effects-file"    , required_argument, NULL, 0},
-  {"temp"            , required_argument, NULL, 0},
-  {"single-threaded" ,       no_argument, NULL, 0},
-  {"ignore-length"   ,       no_argument, NULL, 0},
-  {"norm"            ,       no_argument, NULL, 0},
-  {"magic"           ,       no_argument, NULL, 0},
-  {"play-rate-arg"   , required_argument, NULL, 0},
-  {"clobber"         ,       no_argument, NULL, 0},
-  {"no-clobber"      ,       no_argument, NULL, 0},
-  {"multi-threaded"  ,       no_argument, NULL, 0},
+static struct lsx_option_t const long_options[] = {
+  {"add-comment"     , lsx_option_arg_required, NULL, 0},
+  {"buffer"          , lsx_option_arg_required, NULL, 0},
+  {"combine"         , lsx_option_arg_required, NULL, 0},
+  {"comment-file"    , lsx_option_arg_required, NULL, 0},
+  {"comment"         , lsx_option_arg_required, NULL, 0},
+  {"endian"          , lsx_option_arg_required, NULL, 0},
+  {"input-buffer"    , lsx_option_arg_required, NULL, 0},
+  {"interactive"     , lsx_option_arg_none    , NULL, 0},
+  {"help-effect"     , lsx_option_arg_required, NULL, 0},
+  {"help-format"     , lsx_option_arg_required, NULL, 0},
+  {"no-glob"         , lsx_option_arg_none    , NULL, 0},
+  {"plot"            , lsx_option_arg_required, NULL, 0},
+  {"replay-gain"     , lsx_option_arg_required, NULL, 0},
+  {"version"         , lsx_option_arg_none    , NULL, 0},
+  {"output"          , lsx_option_arg_required, NULL, 0},
+  {"effects-file"    , lsx_option_arg_required, NULL, 0},
+  {"temp"            , lsx_option_arg_required, NULL, 0},
+  {"single-threaded" , lsx_option_arg_none    , NULL, 0},
+  {"ignore-length"   , lsx_option_arg_none    , NULL, 0},
+  {"norm"            , lsx_option_arg_none    , NULL, 0},
+  {"magic"           , lsx_option_arg_none    , NULL, 0},
+  {"play-rate-arg"   , lsx_option_arg_required, NULL, 0},
+  {"clobber"         , lsx_option_arg_none    , NULL, 0},
+  {"no-clobber"      , lsx_option_arg_none    , NULL, 0},
+  {"multi-threaded"  , lsx_option_arg_none    , NULL, 0},
 
-  {"bits"            , required_argument, NULL, 'b'},
-  {"channels"        , required_argument, NULL, 'c'},
-  {"compression"     , required_argument, NULL, 'C'},
-  {"default-device"  ,       no_argument, NULL, 'd'},
-  {"no-dither"       ,       no_argument, NULL, 'D'},
-  {"encoding"        , required_argument, NULL, 'e'},
-  {"help"            ,       no_argument, NULL, 'h'},
-  {"null"            ,       no_argument, NULL, 'n'},
-  {"no-show-progress",       no_argument, NULL, 'q'},
-  {"pipe"            ,       no_argument, NULL, 'p'},
-  {"rate"            , required_argument, NULL, 'r'},
-  {"reverse-bits"    ,       no_argument, NULL, 'X'},
-  {"reverse-nibbles" ,       no_argument, NULL, 'N'},
-  {"show-progress"   ,       no_argument, NULL, 'S'},
-  {"type"            , required_argument, NULL, 't'},
-  {"volume"          , required_argument, NULL, 'v'},
-  {"guard"           ,       no_argument, NULL, 'G'},
+  {"bits"            , lsx_option_arg_required, NULL, 'b'},
+  {"channels"        , lsx_option_arg_required, NULL, 'c'},
+  {"compression"     , lsx_option_arg_required, NULL, 'C'},
+  {"default-device"  , lsx_option_arg_none    , NULL, 'd'},
+  {"no-dither"       , lsx_option_arg_none    , NULL, 'D'},
+  {"encoding"        , lsx_option_arg_required, NULL, 'e'},
+  {"help"            , lsx_option_arg_none    , NULL, 'h'},
+  {"null"            , lsx_option_arg_none    , NULL, 'n'},
+  {"no-show-progress", lsx_option_arg_none    , NULL, 'q'},
+  {"pipe"            , lsx_option_arg_none    , NULL, 'p'},
+  {"rate"            , lsx_option_arg_required, NULL, 'r'},
+  {"reverse-bits"    , lsx_option_arg_none    , NULL, 'X'},
+  {"reverse-nibbles" , lsx_option_arg_none    , NULL, 'N'},
+  {"show-progress"   , lsx_option_arg_none    , NULL, 'S'},
+  {"type"            , lsx_option_arg_required, NULL, 't'},
+  {"volume"          , lsx_option_arg_required, NULL, 'v'},
+  {"guard"           , lsx_option_arg_none    , NULL, 'G'},
 
   {NULL, 0, NULL, 0}
 };
@@ -2122,9 +2119,9 @@
   {"a-law", encoding_a_law},
   {0, 0}};
 
-static int enum_option(int option_index, lsx_enum_item const * items)
+static int enum_option(char const * arg, int option_index, lsx_enum_item const * items)
 {
-  lsx_enum_item const * p = lsx_find_enum_text(lsx_optarg, items, 0);
+  lsx_enum_item const * p = lsx_find_enum_text(arg, items, 0);
   if (p == NULL) {
     size_t len = 1;
     char * set = lsx_malloc(len);
@@ -2134,7 +2131,7 @@
       strcat(set, ", "); strcat(set, p->text);
     }
     lsx_fail("--%s: `%s' is not one of: %s.",
-        long_options[option_index].name, lsx_optarg, set + 2);
+        long_options[option_index].name, arg, set + 2);
     free(set);
     exit(1);
   }
@@ -2141,29 +2138,32 @@
   return p->value;
 }
 
-static char parse_gopts_and_fopts(file_t * f, int argc, char **argv)
+static char parse_gopts_and_fopts(file_t * f, int * argi, int argc, char **argv)
 {
+  lsx_getopt_t optstate;
   const sox_version_info_t* info = sox_version_info();
+  lsx_getopt_init(argc, argv, getoptstr, long_options, lsx_getopt_flag_opterr, *argi, &optstate);
   while (sox_true) {
-    int c, option_index;
+    int c;
     int i; /* sscanf silently accepts negative numbers for %u :( */
     char dummy;     /* To check for extraneous chars in optarg. */
 
-    switch (c=lsx_getopt_long(argc, argv, getoptstr, long_options, &option_index)) {
+    switch (c=lsx_getopt(&optstate)) {
     case -1:        /* @ one of: file-name, effect name, end of arg-list. */
+      *argi = optstate.ind;
       return '\0'; /* i.e. not device. */
 
     case 0:         /* Long options with no short equivalent. */
-      switch (option_index) {
+      switch (optstate.lngind) {
       case 0:
-        if (lsx_optarg)
-          sox_append_comment(&f->oob.comments, lsx_optarg);
+        if (optstate.arg)
+          sox_append_comment(&f->oob.comments, optstate.arg);
         break;
 
       case 1:
 #define SOX_BUFMIN 16
-        if (sscanf(lsx_optarg, "%i %c", &i, &dummy) != 1 || i <= SOX_BUFMIN) {
-          lsx_fail("Buffer size `%s' must be > %d", lsx_optarg, SOX_BUFMIN);
+        if (sscanf(optstate.arg, "%i %c", &i, &dummy) != 1 || i <= SOX_BUFMIN) {
+          lsx_fail("Buffer size `%s' must be > %d", optstate.arg, SOX_BUFMIN);
           exit(1);
         }
         sox_globals.bufsiz = i;
@@ -2170,24 +2170,24 @@
         break;
 
       case 2:
-        combine_method = enum_option(option_index, combine_methods);
+        combine_method = enum_option(optstate.arg, optstate.lngind, combine_methods);
         break;
 
       case 3:
         sox_append_comment(&f->oob.comments, "");
-        read_comment_file(&f->oob.comments, lsx_optarg);
+        read_comment_file(&f->oob.comments, optstate.arg);
         break;
 
       case 4:
         sox_append_comment(&f->oob.comments, "");
-        if (*lsx_optarg)
-          sox_append_comment(&f->oob.comments, lsx_optarg);
+        if (*optstate.arg)
+          sox_append_comment(&f->oob.comments, optstate.arg);
         break;
 
       case 5:
         if (f->encoding.reverse_bytes != SOX_OPTION_DEFAULT || f->encoding.opposite_endian)
           usage("only one endian option per file is allowed");
-        switch (enum_option(option_index, endian_options)) {
+        switch (enum_option(optstate.arg, optstate.lngind, endian_options)) {
           case ENDIAN_little: f->encoding.reverse_bytes = MACHINE_IS_BIGENDIAN; break;
           case ENDIAN_big: f->encoding.reverse_bytes = MACHINE_IS_LITTLEENDIAN; break;
           case ENDIAN_swap: f->encoding.opposite_endian = sox_true; break;
@@ -2195,8 +2195,8 @@
         break;
 
       case 6:
-        if (sscanf(lsx_optarg, "%i %c", &i, &dummy) != 1 || i <= SOX_BUFMIN) {
-          lsx_fail("Buffer size `%s' must be > %d", lsx_optarg, SOX_BUFMIN);
+        if (sscanf(optstate.arg, "%i %c", &i, &dummy) != 1 || i <= SOX_BUFMIN) {
+          lsx_fail("Buffer size `%s' must be > %d", optstate.arg, SOX_BUFMIN);
           exit(1);
         }
         sox_globals.input_bufsiz = i;
@@ -2203,17 +2203,17 @@
         break;
 
       case 7: no_clobber = sox_true; break;
-      case 8: usage_effect(lsx_optarg); break;
-      case 9: usage_format(lsx_optarg); break;
+      case 8: usage_effect(optstate.arg); break;
+      case 9: usage_format(optstate.arg); break;
       case 10: f->no_glob = sox_true; break;
       case 11:
-        sox_effects_globals.plot = enum_option(option_index, plot_methods);
+        sox_effects_globals.plot = enum_option(optstate.arg, optstate.lngind, plot_methods);
         break;
-      case 12: replay_gain_mode = enum_option(option_index, rg_modes); break;
+      case 12: replay_gain_mode = enum_option(optstate.arg, optstate.lngind, rg_modes); break;
       case 13: display_SoX_version(stdout); exit(0); break;
       case 14: break;
-      case 15: effects_filename = strdup(lsx_optarg); break;
-      case 16: sox_globals.tmp_path = strdup(lsx_optarg); break;
+      case 15: effects_filename = strdup(optstate.arg); break;
+      case 16: sox_globals.tmp_path = strdup(optstate.arg); break;
       case 17: sox_globals.use_threads = sox_false; break;
       case 18: f->signal.length = SOX_IGNORE_LENGTH; break;
       case 19: do_guarded_norm = is_guarded = sox_true; break;
@@ -2223,7 +2223,7 @@
         else
           lsx_warn("this build of SoX does not include `magic'");
         break;
-      case 21: play_rate_arg = strdup(lsx_optarg); break;
+      case 21: play_rate_arg = strdup(optstate.arg); break;
       case 22: no_clobber = sox_false; break;
       case 23: no_clobber = sox_true; break;
       case 24: sox_globals.use_threads = sox_true; break;
@@ -2240,8 +2240,8 @@
       break;
 
     case 'd': case 'n': case 'p':
+      *argi = optstate.ind;
       return c;
-      break;
 
     case 'h':
       usage(NULL);
@@ -2252,7 +2252,7 @@
       break;
 
     case 't':
-      f->filetype = lsx_optarg;
+      f->filetype = optstate.arg;
       if (f->filetype[0] == '.')
         f->filetype++;
       break;
@@ -2259,9 +2259,9 @@
 
     case 'r': {
       char k = 0;
-      size_t n = sscanf(lsx_optarg, "%lf %c %c", &f->signal.rate, &k, &dummy);
+      size_t n = sscanf(optstate.arg, "%lf %c %c", &f->signal.rate, &k, &dummy);
       if (n < 1 || f->signal.rate <= 0 || (n > 1 && k != 'k') || n > 2) {
-        lsx_fail("Rate value `%s' is not a positive number", lsx_optarg);
+        lsx_fail("Rate value `%s' is not a positive number", optstate.arg);
         exit(1);
       }
       f->signal.rate *= k == 'k'? 1000. : 1.;
@@ -2269,8 +2269,8 @@
     }
 
     case 'v':
-      if (sscanf(lsx_optarg, "%lf %c", &f->volume, &dummy) != 1) {
-        lsx_fail("Volume value `%s' is not a number", lsx_optarg);
+      if (sscanf(optstate.arg, "%lf %c", &f->volume, &dummy) != 1) {
+        lsx_fail("Volume value `%s' is not a number", optstate.arg);
         exit(1);
       }
       uservolume = sox_true;
@@ -2280,8 +2280,8 @@
       break;
 
     case 'c':
-      if (sscanf(lsx_optarg, "%d %c", &i, &dummy) != 1 || i <= 0) {
-        lsx_fail("Channels value `%s' is not a positive integer", lsx_optarg);
+      if (sscanf(optstate.arg, "%d %c", &i, &dummy) != 1 || i <= 0) {
+        lsx_fail("Channels value `%s' is not a positive integer", optstate.arg);
         exit(1);
       }
       f->signal.channels = i;
@@ -2288,21 +2288,21 @@
       break;
 
     case 'C':
-      if (sscanf(lsx_optarg, "%lf %c", &f->encoding.compression, &dummy) != 1) {
-        lsx_fail("Compression value `%s' is not a number", lsx_optarg);
+      if (sscanf(optstate.arg, "%lf %c", &f->encoding.compression, &dummy) != 1) {
+        lsx_fail("Compression value `%s' is not a number", optstate.arg);
         exit(1);
       }
       break;
 
     case 'b':
-      if (sscanf(lsx_optarg, "%d %c", &i, &dummy) != 1 || i <= 0) {
-        lsx_fail("Bits value `%s' is not a positive integer", lsx_optarg);
+      if (sscanf(optstate.arg, "%d %c", &i, &dummy) != 1 || i <= 0) {
+        lsx_fail("Bits value `%s' is not a positive integer", optstate.arg);
         exit(1);
       }
       f->encoding.bits_per_sample = i;
       break;
 
-    case 'e': switch (enum_option(opt_index('e'), encodings)) {
+    case 'e': switch (enum_option(optstate.arg, opt_index('e'), encodings)) {
       case encoding_signed_integer:   f->encoding.encoding = SOX_ENCODING_SIGN2;     break;
       case encoding_unsigned_integer: f->encoding.encoding = SOX_ENCODING_UNSIGNED;  break;
       case encoding_floating_point:   f->encoding.encoding = SOX_ENCODING_FLOAT;     break;
@@ -2362,12 +2362,12 @@
     case 'D': no_dither = sox_true; break;
 
     case 'V':
-      if (lsx_optarg == NULL)
+      if (optstate.arg == NULL)
         ++sox_globals.verbosity;
       else {
-        if (sscanf(lsx_optarg, "%d %c", &i, &dummy) != 1 || i < 0) {
+        if (sscanf(optstate.arg, "%d %c", &i, &dummy) != 1 || i < 0) {
           sox_globals.verbosity = 2;
-          lsx_fail("Verbosity value `%s' is not a non-negative integer", lsx_optarg);
+          lsx_fail("Verbosity value `%s' is not a non-negative integer", optstate.arg);
           exit(1);
         }
         sox_globals.verbosity = (unsigned)i;
@@ -2466,7 +2466,7 @@
   f->replay_gain = HUGE_VAL;
 }
 
-static void parse_options_and_filenames(int argc, char **argv)
+static void parse_options_and_filenames(int * argi, int argc, char **argv)
 {
   char const * env_opts = getenv(SOX_OPTS);
   file_t opts, opts_none;
@@ -2478,21 +2478,21 @@
   if (env_opts && *env_opts) {
     char * * argv2, * str = lsx_malloc(strlen(argv[0]) + strlen(env_opts) + 2);
     int argc2;
+    int argi2 = 1;
     strcpy(str, argv[0]);
     strcat(str, " ");
     strcat(str, env_opts);
     argv2 = strtoargv(str, &argc2);
-    if (parse_gopts_and_fopts(&opts, argc2, argv2)) {
+    if (parse_gopts_and_fopts(&opts, &argi2, argc2, argv2)) {
       lsx_fail("invalid option for "SOX_OPTS);
       exit(1);
     }
-    lsx_optind = 1, opterr = 0;
     free(str);
     free(argv2);
   }
 
-  for (; lsx_optind < argc && !sox_find_effect(argv[lsx_optind]); init_file(&opts)) {
-    char c = parse_gopts_and_fopts(&opts, argc, argv);
+  for (; *argi < argc && !sox_find_effect(argv[*argi]); init_file(&opts)) {
+    char c = parse_gopts_and_fopts(&opts, argi, argc, argv);
     if (c == 'n') { /* is null file? */
       if (opts.filetype != NULL && strcmp(opts.filetype, "null") != 0)
         lsx_warn("ignoring `-t %s'.", opts.filetype);
@@ -2507,11 +2507,11 @@
       opts.filetype = "sox";
       add_file(&opts, "-");
     }
-    else if (lsx_optind >= argc || sox_find_effect(argv[lsx_optind]))
+    else if (*argi >= argc || sox_find_effect(argv[*argi]))
       break;
-    else if (!sox_is_playlist(argv[lsx_optind]))
-      add_glob_file(&opts, argv[lsx_optind++]);
-    else if (sox_parse_playlist((sox_playlist_callback_t)add_file, &opts, argv[lsx_optind++]) != SOX_SUCCESS)
+    else if (!sox_is_playlist(argv[*argi]))
+      add_glob_file(&opts, argv[(*argi)++]);
+    else if (sox_parse_playlist((sox_playlist_callback_t)add_file, &opts, argv[(*argi)++]) != SOX_SUCCESS)
       exit(1);
   }
   if (env_opts && *env_opts) {
@@ -2530,7 +2530,7 @@
 typedef enum {Full, Type, Rate, Channels, Samples, Duration, Duration_secs,
     Bits, Bitrate, Encoding, Annotation} soxi_t;
 
-static int soxi1(soxi_t const * type, char * filename)
+static int soxi1(soxi_t const * type, char const * filename)
 {
   sox_format_t * ft = sox_open_read(filename, NULL, NULL, NULL);
   double secs;
@@ -2594,25 +2594,27 @@
   exit(return_code);
 }
 
-static int soxi(int argc, char * const * argv)
+static int soxi(int * argi, int argc, char * const * argv)
 {
   static char const opts[] = "trcsdDbBea?TV::";
   soxi_t type = Full;
   int opt, num_errors = 0;
   sox_bool do_total = sox_false;
+  lsx_getopt_t optstate;
 
-  if (argc < 2)
+  if (argc - *argi < 1)
     soxi_usage(0);
-  while ((opt = lsx_getopt(argc, argv, opts)) > 0) /* act only on last option */
+  lsx_getopt_init(argc, argv, opts, NULL, lsx_getopt_flag_opterr, *argi, &optstate);
+  while ((opt = lsx_getopt(&optstate)) > 0) /* act only on last option */
     if (opt == 'V') {
       int i; /* sscanf silently accepts negative numbers for %u :( */
-      char dummy;     /* To check for extraneous chars in optarg. */
-      if (lsx_optarg == NULL)
+      char dummy;     /* To check for extraneous chars in optstate.arg. */
+      if (optstate.arg == NULL)
         ++sox_globals.verbosity;
       else {
-        if (sscanf(lsx_optarg, "%d %c", &i, &dummy) != 1 || i < 0) {
+        if (sscanf(optstate.arg, "%d %c", &i, &dummy) != 1 || i < 0) {
           sox_globals.verbosity = 2;
-          lsx_fail("Verbosity value `%s' is not a non-negative integer", lsx_optarg);
+          lsx_fail("Verbosity value `%s' is not a non-negative integer", optstate.arg);
           exit(1);
         }
         sox_globals.verbosity = (unsigned)i;
@@ -2630,10 +2632,10 @@
     do_total = sox_false;
   }
   soxi_total = -!do_total;
-  for (; lsx_optind < argc; ++lsx_optind) {
-    if (sox_is_playlist(argv[lsx_optind]))
-      num_errors += (sox_parse_playlist((sox_playlist_callback_t)soxi1, &type, argv[lsx_optind]) != SOX_SUCCESS);
-    else num_errors += soxi1(&type, argv[lsx_optind]);
+  for (; optstate.ind < argc; ++optstate.ind) {
+    if (sox_is_playlist(argv[optstate.ind]))
+      num_errors += (sox_parse_playlist((sox_playlist_callback_t)soxi1, &type, argv[optstate.ind]) != SOX_SUCCESS);
+    else num_errors += soxi1(&type, argv[optstate.ind]);
   }
   if (type == Full) {
     if (soxi_file_count > 1 && soxi_total > 0)
@@ -2698,6 +2700,7 @@
 int main(int argc, char **argv)
 {
   size_t i;
+  int argi = 1;
 
   myname = argv[0];
   sox_globals.output_message_handler = output_message;
@@ -2711,7 +2714,7 @@
 
   if (!sox_mode && argc > 1 &&
       (!strcmp(argv[1], "--i") || !strcmp(argv[1], "--info")))
-    --argc, ++argv, sox_mode = sox_soxi;
+    ++argi, sox_mode = sox_soxi;
 
   if (sox_init() != SOX_SUCCESS)
     exit(1);
@@ -2722,9 +2725,9 @@
   atexit(cleanup);
 
   if (sox_mode == sox_soxi)
-    exit(soxi(argc, argv));
+    exit(soxi(&argi, argc, argv));
 
-  parse_options_and_filenames(argc, argv);
+  parse_options_and_filenames(&argi, argc, argv);
 
 #if defined(__CYGWIN__) || defined(__MINGW32__) 
   /* Workarounds for a couple of cygwin/mingw problems: */
@@ -2832,7 +2835,7 @@
   init_eff_chains();
 
   /* Loop through the rest of the arguments looking for effects */
-  parse_effects(argc, argv);
+  parse_effects(&argi, argc, argv);
   if (eff_chain_count == 0 || nuser_effects[eff_chain_count] > 0)
   {
     eff_chain_count++;
--- a/src/sox.h
+++ b/src/sox.h
@@ -1297,16 +1297,17 @@
 SOX_API lsx_find_enum_value(
     unsigned value,
     LSX_PARAM_IN lsx_enum_item const * lsx_enum_items);
-int
-SOX_API LSX_RETURN_PURE lsx_enum_option(
+LSX_RETURN_PURE int
+SOX_API lsx_enum_option(
     int c,
+    LSX_PARAM_IN_Z char const * arg,
     LSX_PARAM_IN lsx_enum_item const * items);
-sox_bool
-SOX_API LSX_RETURN_PURE lsx_strends(
+LSX_RETURN_PURE sox_bool
+SOX_API lsx_strends(
     LSX_PARAM_IN_Z char const * str,
     LSX_PARAM_IN_Z char const * end);
-LSX_RETURN_VALID_Z char const *
-SOX_API LSX_RETURN_PURE lsx_find_file_extension(
+LSX_RETURN_VALID_Z LSX_RETURN_PURE char const *
+SOX_API lsx_find_file_extension(
     LSX_PARAM_IN_Z char const * pathname);
 LSX_RETURN_VALID_Z char const *
 SOX_API lsx_sigfigs3(
@@ -1318,15 +1319,69 @@
 SOX_API lsx_realloc(
     LSX_PARAM_IN_OPT void *ptr,
     size_t newsize);
-int
-SOX_API LSX_RETURN_PURE lsx_strcasecmp(
+LSX_RETURN_PURE int
+SOX_API lsx_strcasecmp(
     LSX_PARAM_IN_Z const char * s1,
     LSX_PARAM_IN_Z const char * s2);
-int
-SOX_API LSX_RETURN_PURE lsx_strncasecmp(
+LSX_RETURN_PURE int
+SOX_API lsx_strncasecmp(
     LSX_PARAM_IN_Z char const * s1,
     LSX_PARAM_IN_Z char const * s2,
     size_t n);
+
+typedef enum lsx_option_arg_t {
+    lsx_option_arg_none,
+    lsx_option_arg_required,
+    lsx_option_arg_optional
+} lsx_option_arg_t;
+
+typedef struct lsx_option_t {
+    char const *     name;
+    lsx_option_arg_t has_arg;
+    int *            flag;
+    int              val;
+} lsx_option_t;
+
+typedef enum lsx_getopt_flags_t {
+    lsx_getopt_flag_none = 0,      /* no flags (no output, not long-only) */
+    lsx_getopt_flag_opterr = 1,    /* if set, invalid options trigger lsx_warn output */
+    lsx_getopt_flag_longonly = 2   /* if set, recognize accept -option as a long option */
+} lsx_getopt_flags_t;
+
+typedef struct lsx_getopt_t {
+    int                  argc;     /* IN    argc:      Number of arguments in argv */
+    char * const *       argv;     /* IN    argv:      Array of arguments */
+    char const *         shortopts;/* IN    shortopts: Short option characters */
+    lsx_option_t const * longopts; /* IN    longopts:  Array of long option descriptors */
+    lsx_getopt_flags_t   flags;    /* IN    flags:     Flags for longonly and opterr */
+    char const *         curpos;   /* INOUT curpos:    Maintains state between calls to lsx_getopt */
+    int                  ind;      /* INOUT optind:    Maintains the index of next element to be processed */
+    int                  opt;      /* OUT   optopt:    Receives the option character that caused error */
+    char const *         arg;      /* OUT   optarg:    Receives the value of the option's argument */
+    int                  lngind;   /* OUT   lngind:    Receives the index of the matched long option or -1 if not a long option */
+} lsx_getopt_t;
+
+/* Initializes an lsx_getopt_t structure for use with lsx_getopt. */
+void
+SOX_API lsx_getopt_init(
+    LSX_PARAM_IN             int argc,                      /* Number of arguments in argv */
+    LSX_PARAM_IN_COUNT(argc) char * const * argv,           /* Array of arguments */
+    LSX_PARAM_IN_Z           char const * shortopts,        /* Short options, i.e. ":abc:def::ghi" (+/- not supported) */
+    LSX_PARAM_IN_OPT         lsx_option_t const * longopts, /* Array of long option descriptors */
+    LSX_PARAM_IN             lsx_getopt_flags_t flags,      /* Flags for longonly and opterr */
+    LSX_PARAM_IN             int first,                     /* First argv to check (usually 1) */
+    LSX_PARAM_OUT            lsx_getopt_t * state);         /* State object to be initialized */
+
+/* Gets the next option. Options are parameters that start with "-" or "--".
+ * If no more options, returns -1. If unrecognized short option, returns '?'.
+ * If a recognized short option is missing a required argument,
+ * return (shortopts[0]==':' ? ':' : '?'). If successfully recognized short
+ * option, return the recognized character. If successfully recognized long
+ * option, returns (option.flag ? 0 : option.val).
+ * Note: lsx_getopt does not permute the non-option arguments. */
+int /* Returns option character (short), val or 0 (long), or -1 (no more) */
+SOX_API lsx_getopt(
+    LSX_PARAM_INOUT lsx_getopt_t * state);
 
 /* WARNING END */
 
--- a/src/sox_i.h
+++ b/src/sox_i.h
@@ -287,10 +287,10 @@
   } \
 }
 
-#define GETOPT_NUMERIC(ch, name, min, max) case ch:{ \
+#define GETOPT_NUMERIC(state, ch, name, min, max) case ch:{ \
   char * end_ptr; \
-  double d = strtod(lsx_optarg, &end_ptr); \
-  if (end_ptr == lsx_optarg || d < min || d > max || *end_ptr != '\0') {\
+  double d = strtod(state.arg, &end_ptr); \
+  if (end_ptr == state.arg || d < min || d > max || *end_ptr != '\0') {\
     lsx_fail("parameter `%s' must be between %g and %g", #name, (double)min, (double)max); \
     return lsx_usage(effp); \
   } \
--- a/src/spectrogram.c
+++ b/src/spectrogram.c
@@ -21,7 +21,6 @@
 
 #include "sox_i.h"
 #include "fft4g.h"
-#include "sgetopt.h"
 #include <assert.h>
 #include <math.h>
 #ifdef HAVE_LIBPNG_PNG_H
@@ -96,21 +95,23 @@
   size_t duration;
   char const * next;
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, "+S:d:x:X:y:Y:z:Z:q:p:W:w:st:c:AarmlhTo:", NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->dB_range = 120, p->spectrum_points = 249, p->perm = 1; /* Non-0 defaults */
   p->out_name = "spectrogram.png", p->comment = "Created by SoX";
 
-  while ((c = lsx_getopt(argc, argv, "+S:d:x:X:y:Y:z:Z:q:p:W:w:st:c:AarmlhTo:")) != -1) switch (c) {
-    GETOPT_NUMERIC('x', x_size0       , 100, 5000)
-    GETOPT_NUMERIC('X', pixels_per_sec,  1 , 5000)
-    GETOPT_NUMERIC('y', y_size        , 64 , 1200)
-    GETOPT_NUMERIC('Y', Y_size        , 130, MAX_FFT_SIZE / 2 + 2)
-    GETOPT_NUMERIC('z', dB_range      , 20 , 180)
-    GETOPT_NUMERIC('Z', gain          ,-100, 100)
-    GETOPT_NUMERIC('q', spectrum_points, 0 , p->spectrum_points)
-    GETOPT_NUMERIC('p', perm          ,  1 , 6)
-    GETOPT_NUMERIC('W', window_adjust , -10, 10)
-    case 'w': p->win_type = lsx_enum_option(c, window_options);   break;
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
+    GETOPT_NUMERIC(optstate, 'x', x_size0       , 100, 5000)
+    GETOPT_NUMERIC(optstate, 'X', pixels_per_sec,  1 , 5000)
+    GETOPT_NUMERIC(optstate, 'y', y_size        , 64 , 1200)
+    GETOPT_NUMERIC(optstate, 'Y', Y_size        , 130, MAX_FFT_SIZE / 2 + 2)
+    GETOPT_NUMERIC(optstate, 'z', dB_range      , 20 , 180)
+    GETOPT_NUMERIC(optstate, 'Z', gain          ,-100, 100)
+    GETOPT_NUMERIC(optstate, 'q', spectrum_points, 0 , p->spectrum_points)
+    GETOPT_NUMERIC(optstate, 'p', perm          ,  1 , 6)
+    GETOPT_NUMERIC(optstate, 'W', window_adjust , -10, 10)
+    case 'w': p->win_type = lsx_enum_option(c, optstate.arg, window_options);   break;
     case 's': p->slack_overlap    = sox_true;   break;
     case 'A': p->alt_palette      = sox_true;   break;
     case 'a': p->no_axes          = sox_true;   break;
@@ -119,16 +120,16 @@
     case 'l': p->light_background = sox_true;   break;
     case 'h': p->high_colour      = sox_true;   break;
     case 'T': p->truncate         = sox_true;   break;
-    case 't': p->title            = lsx_optarg; break;
-    case 'c': p->comment          = lsx_optarg; break;
-    case 'o': p->out_name         = lsx_optarg; break;
-    case 'S': next = lsx_parsesamples(1e5, lsx_optarg, &duration, 't');
+    case 't': p->title            = optstate.arg; break;
+    case 'c': p->comment          = optstate.arg; break;
+    case 'o': p->out_name         = optstate.arg; break;
+    case 'S': next = lsx_parsesamples(1e5, optstate.arg, &duration, 't');
       if (next && !*next) {p->start_time = duration * 1e-5; break;}
       return lsx_usage(effp);
-    case 'd': next = lsx_parsesamples(1e5, lsx_optarg, &duration, 't');
+    case 'd': next = lsx_parsesamples(1e5, optstate.arg, &duration, 't');
       if (next && !*next) {p->duration = duration * 1e-5; break;}
       return lsx_usage(effp);
-    default: lsx_fail("invalid option `-%c'", optopt); return lsx_usage(effp);
+    default: lsx_fail("invalid option `-%c'", optstate.opt); return lsx_usage(effp);
   }
   if (!!p->x_size0 + !!p->pixels_per_sec + !!p->duration > 2) {
     lsx_fail("only two of -x, -X, -d may be given");
@@ -144,7 +145,7 @@
   if (p->alt_palette)
     p->spectrum_points = min(p->spectrum_points, (int)alt_palette_len);
   p->shared_ptr = &p->shared;
-  return lsx_optind !=argc || p->win_type == INT_MAX? lsx_usage(effp) : SOX_SUCCESS;
+  return optstate.ind !=argc || p->win_type == INT_MAX? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static double make_window(priv_t * p, int end)
--- a/src/stats.c
+++ b/src/stats.c
@@ -16,7 +16,6 @@
  */
 
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <ctype.h>
 #include <string.h>
 
@@ -34,19 +33,21 @@
 {
   priv_t * p = (priv_t *)effp->priv;
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, "+x:b:w:s:", NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->time_constant = .05;
   p->scale = 1;
-  while ((c = lsx_getopt(argc, argv, "+x:b:w:s:")) != -1) switch (c) {
-    GETOPT_NUMERIC('x', hex_bits      ,  2 , 32)
-    GETOPT_NUMERIC('b', scale_bits    ,  2 , 32)
-    GETOPT_NUMERIC('w', time_constant ,  .01 , 10)
-    GETOPT_NUMERIC('s', scale         ,  -99, 99)
-    default: lsx_fail("invalid option `-%c'", optopt); return lsx_usage(effp);
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
+    GETOPT_NUMERIC(optstate, 'x', hex_bits      ,  2 , 32)
+    GETOPT_NUMERIC(optstate, 'b', scale_bits    ,  2 , 32)
+    GETOPT_NUMERIC(optstate, 'w', time_constant ,  .01 , 10)
+    GETOPT_NUMERIC(optstate, 's', scale         ,  -99, 99)
+    default: lsx_fail("invalid option `-%c'", optstate.opt); return lsx_usage(effp);
   }
   if (p->hex_bits)
     p->scale_bits = p->hex_bits;
-  return lsx_optind != argc? lsx_usage(effp) : SOX_SUCCESS;
+  return optstate.ind != argc? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static int start(sox_effect_t * effp)
--- a/src/tempo.c
+++ b/src/tempo.c
@@ -19,7 +19,6 @@
 
 #include "sox_i.h"
 #include "fifo.h"
-#include "sgetopt.h"
 #include <math.h>
 
 typedef struct {
@@ -216,16 +215,18 @@
   static const double overlaps_div[] = {6.833, 7,  2.5 , 2};
   static const double searches_div[] = {5.587, 6,  2.14, 2};
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, "+qmls", NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->segment_ms = p->search_ms = p->overlap_ms = HUGE_VAL;
-  while ((c = lsx_getopt(argc, argv, "+qmls")) != -1) switch (c) {
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
     case 'q': p->quick_search  = sox_true;   break;
     case 'm': profile = Music; break;
     case 's': profile = Speech; break;
     case 'l': profile = Linear; p->search_ms = 0; break;
-    default: lsx_fail("unknown option `-%c'", optopt); return lsx_usage(effp);
+    default: lsx_fail("unknown option `-%c'", optstate.opt); return lsx_usage(effp);
   }
-  argc -= lsx_optind, argv += lsx_optind;
+  argc -= optstate.ind, argv += optstate.ind;
   do {                    /* break-able block */
     NUMERIC_PARAMETER(factor      ,0.1 , 100 )
     NUMERIC_PARAMETER(segment_ms  , 10 , 120)
--- a/src/util.c
+++ b/src/util.c
@@ -17,7 +17,6 @@
  */
 
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <ctype.h>
 #include <stdio.h>
 
@@ -96,9 +95,9 @@
   return NULL;
 }
 
-int lsx_enum_option(int c, lsx_enum_item const * items)
+int lsx_enum_option(int c, char const * arg, lsx_enum_item const * items)
 {
-  lsx_enum_item const * p = lsx_find_enum_text(lsx_optarg, items, sox_false);
+  lsx_enum_item const * p = lsx_find_enum_text(arg, items, sox_false);
   if (p == NULL) {
     size_t len = 1;
     char * set = lsx_malloc(len);
@@ -107,7 +106,7 @@
       set = lsx_realloc(set, len += 2 + strlen(p->text));
       strcat(set, ", "); strcat(set, p->text);
     }
-    lsx_fail("-%c: `%s' is not one of: %s.", c, lsx_optarg, set + 2);
+    lsx_fail("-%c: `%s' is not one of: %s.", c, arg, set + 2);
     free(set);
     return INT_MAX;
   }
--- a/src/vad.c
+++ b/src/vad.c
@@ -16,7 +16,6 @@
  */
 
 #include "sox_i.h"
-#include "sgetopt.h"
 #include <string.h>
 
 typedef struct {
@@ -41,8 +40,8 @@
   chan_t    * channels;
 } priv_t;
 
-#define GETOPT_FREQ(c, name, min) \
-    case c: p->name = lsx_parse_frequency(lsx_optarg, &parseIndex); \
+#define GETOPT_FREQ(optstate, c, name, min) \
+    case c: p->name = lsx_parse_frequency(optstate.arg, &parseIndex); \
       if (p->name < min || *parseIndex) return lsx_usage(effp); \
       break;
 
@@ -51,6 +50,8 @@
   priv_t * p = (priv_t *)effp->priv;
   #define opt_str "+b:N:n:r:f:m:M:h:l:H:L:T:t:s:g:p:"
   int c;
+  lsx_getopt_t optstate;
+  lsx_getopt_init(argc, argv, opt_str, NULL, lsx_getopt_flag_none, 1, &optstate);
 
   p->bootTime        = .35;
   p->noiseTcUp       = .1;
@@ -72,27 +73,27 @@
   p->searchTime      = 1;
   p->gapTime         = .25;
 
-  while ((c = lsx_getopt(argc, argv, opt_str)) != -1) switch (c) {
+  while ((c = lsx_getopt(&optstate)) != -1) switch (c) {
     char * parseIndex;
-    GETOPT_NUMERIC('b', bootTime      ,  .1 , 10)
-    GETOPT_NUMERIC('N', noiseTcUp     ,  .1 , 10)
-    GETOPT_NUMERIC('n', noiseTcDown   ,.001 , .1)
-    GETOPT_NUMERIC('r', noiseReductionAmount,0 , 2)
-    GETOPT_NUMERIC('f', measureFreq   ,   5 , 50)
-    GETOPT_NUMERIC('m', measureDuration, .01 , 1)
-    GETOPT_NUMERIC('M', measureTc     ,  .1 , 1)
-    GETOPT_FREQ(   'h', hpFilterFreq  ,  10)
-    GETOPT_FREQ(   'l', lpFilterFreq  ,  1000)
-    GETOPT_FREQ(   'H', hpLifterFreq  ,  10)
-    GETOPT_FREQ(   'L', lpLifterFreq  ,  1000)
-    GETOPT_NUMERIC('T', triggerTc     , .01 , 1)
-    GETOPT_NUMERIC('t', triggerLevel  ,   0 , 20)
-    GETOPT_NUMERIC('s', searchTime    ,  .1 , 4)
-    GETOPT_NUMERIC('g', gapTime       ,  .1 , 1)
-    GETOPT_NUMERIC('p', preTriggerTime,   0 , 4)
-    default: lsx_fail("invalid option `-%c'", optopt); return lsx_usage(effp);
+    GETOPT_NUMERIC(optstate, 'b', bootTime      ,  .1 , 10)
+    GETOPT_NUMERIC(optstate, 'N', noiseTcUp     ,  .1 , 10)
+    GETOPT_NUMERIC(optstate, 'n', noiseTcDown   ,.001 , .1)
+    GETOPT_NUMERIC(optstate, 'r', noiseReductionAmount,0 , 2)
+    GETOPT_NUMERIC(optstate, 'f', measureFreq   ,   5 , 50)
+    GETOPT_NUMERIC(optstate, 'm', measureDuration, .01 , 1)
+    GETOPT_NUMERIC(optstate, 'M', measureTc     ,  .1 , 1)
+    GETOPT_FREQ(   optstate, 'h', hpFilterFreq  ,  10)
+    GETOPT_FREQ(   optstate, 'l', lpFilterFreq  ,  1000)
+    GETOPT_FREQ(   optstate, 'H', hpLifterFreq  ,  10)
+    GETOPT_FREQ(   optstate, 'L', lpLifterFreq  ,  1000)
+    GETOPT_NUMERIC(optstate, 'T', triggerTc     , .01 , 1)
+    GETOPT_NUMERIC(optstate, 't', triggerLevel  ,   0 , 20)
+    GETOPT_NUMERIC(optstate, 's', searchTime    ,  .1 , 4)
+    GETOPT_NUMERIC(optstate, 'g', gapTime       ,  .1 , 1)
+    GETOPT_NUMERIC(optstate, 'p', preTriggerTime,   0 , 4)
+    default: lsx_fail("invalid option `-%c'", optstate.opt); return lsx_usage(effp);
   }
-  return lsx_optind !=argc? lsx_usage(effp) : SOX_SUCCESS;
+  return optstate.ind !=argc? lsx_usage(effp) : SOX_SUCCESS;
 }
 
 static int start(sox_effect_t * effp)