[libsigrokdecode] 03/08: New upstream version 0.4.1

Zoltan Gyarmati zgyarmati-guest at moszumanska.debian.org
Wed Mar 29 21:40:24 UTC 2017


This is an automated email from the git hooks/post-receive script.

zgyarmati-guest pushed a commit to branch master
in repository libsigrokdecode.

commit 7ed2c441dd8259eb7b75818f6b0564fe076d11f7
Author: Zoltan Gyarmati <Zoltan Gyarmati mr.zoltan.gyarmati at gmail.com>
Date:   Tue Feb 28 23:08:07 2017 +0100

    New upstream version 0.4.1
---
 ChangeLog                                          | 2013 ++++++-
 Doxyfile                                           |    2 +-
 HACKING                                            |   20 +-
 Makefile.am                                        |   59 +-
 Makefile.in                                        |  628 +--
 NEWS                                               |  236 +-
 README                                             |   23 +-
 aclocal.m4                                         |  503 +-
 autostuff/ar-lib                                   |    2 +-
 autostuff/compile                                  |    2 +-
 autostuff/config.guess                             |  354 +-
 autostuff/config.sub                               |   88 +-
 autostuff/depcomp                                  |    2 +-
 autostuff/install-sh                               |  373 +-
 autostuff/ltmain.sh                                | 5533 +++++++++++++-------
 autostuff/missing                                  |    2 +-
 autostuff/test-driver                              |   15 +-
 config.h.in                                        |   50 +-
 configure                                          | 5239 ++++++++----------
 configure.ac                                       |  237 +-
 decoder.c                                          |  994 ++--
 decoders/{ir_nec => adns5020}/__init__.py          |    8 +-
 decoders/adns5020/pd.py                            |  113 +
 decoders/{dcf77 => am230x}/__init__.py             |   21 +-
 decoders/am230x/pd.py                              |  235 +
 decoders/{ir_nec => arm_etmv3}/__init__.py         |    8 +-
 decoders/arm_etmv3/pd.py                           |  564 ++
 decoders/{dcf77 => arm_itm}/__init__.py            |   12 +-
 decoders/arm_itm/pd.py                             |  370 ++
 decoders/{dcf77 => arm_tpiu}/__init__.py           |   14 +-
 decoders/arm_tpiu/pd.py                            |  128 +
 decoders/{dcf77 => aud}/__init__.py                |   14 +-
 decoders/aud/pd.py                                 |  114 +
 decoders/avr_isp/__init__.py                       |    3 +-
 decoders/avr_isp/parts.py                          |    1 -
 decoders/avr_isp/pd.py                             |   17 +-
 decoders/avr_pdi/__init__.py                       |   41 +
 decoders/avr_pdi/pd.py                             |  586 +++
 decoders/can/__init__.py                           |    3 +-
 decoders/can/pd.py                                 |   26 +-
 decoders/{tlc5620 => common}/__init__.py           |    8 +-
 decoders/{tlc5620 => common/plugtrx}/__init__.py   |   14 +-
 decoders/common/plugtrx/mod.py                     |  192 +
 decoders/{tlc5620 => common/sdcard}/__init__.py    |    9 +-
 decoders/common/sdcard/mod.py                      |  186 +
 decoders/{tlc5620 => common/srdhelper}/__init__.py |    9 +-
 .../__init__.py => common/srdhelper/mod.py}        |   11 +-
 decoders/dcf77/__init__.py                         |    3 +-
 decoders/dcf77/pd.py                               |   18 +-
 decoders/{ir_nec => dmx512}/__init__.py            |    8 +-
 decoders/dmx512/pd.py                              |  170 +
 decoders/ds1307/__init__.py                        |    3 +-
 decoders/ds1307/pd.py                              |  238 +-
 decoders/edid/__init__.py                          |    3 +-
 decoders/edid/pd.py                                |   71 +-
 decoders/{ir_rc5 => eeprom24xx}/__init__.py        |    6 +-
 decoders/eeprom24xx/lists.py                       |  171 +
 decoders/eeprom24xx/pd.py                          |  430 ++
 decoders/{ir_nec => em4100}/__init__.py            |    7 +-
 decoders/em4100/pd.py                              |  237 +
 decoders/{tlc5620 => em4305}/__init__.py           |    7 +-
 decoders/em4305/pd.py                              |  396 ++
 decoders/{ir_nec => gpib}/__init__.py              |    7 +-
 decoders/gpib/pd.py                                |  189 +
 decoders/guess_bitrate/__init__.py                 |    3 +-
 decoders/guess_bitrate/pd.py                       |   18 +-
 decoders/i2c/__init__.py                           |    3 +-
 decoders/i2c/pd.py                                 |   24 +-
 decoders/i2cdemux/__init__.py                      |    3 +-
 decoders/i2cdemux/pd.py                            |    3 +-
 decoders/i2cfilter/__init__.py                     |    3 +-
 decoders/i2cfilter/pd.py                           |    6 +-
 decoders/i2s/__init__.py                           |    3 +-
 decoders/i2s/pd.py                                 |   38 +-
 decoders/ir_nec/__init__.py                        |    3 +-
 decoders/ir_nec/lists.py                           |    1 -
 decoders/ir_nec/pd.py                              |   12 +-
 decoders/ir_rc5/__init__.py                        |    3 +-
 decoders/ir_rc5/lists.py                           |    1 -
 decoders/ir_rc5/pd.py                              |   24 +-
 decoders/{dcf77 => jitter}/__init__.py             |   13 +-
 decoders/jitter/pd.py                              |  203 +
 decoders/jtag/__init__.py                          |    3 +-
 decoders/jtag/pd.py                                |   95 +-
 decoders/jtag_stm32/__init__.py                    |    3 +-
 decoders/jtag_stm32/pd.py                          |  125 +-
 decoders/lm75/__init__.py                          |    3 +-
 decoders/lm75/pd.py                                |   11 +-
 decoders/lpc/__init__.py                           |    3 +-
 decoders/lpc/pd.py                                 |    7 +-
 decoders/{ir_nec => max7219}/__init__.py           |    8 +-
 decoders/max7219/pd.py                             |  109 +
 decoders/maxim_ds28ea00/__init__.py                |    3 +-
 decoders/maxim_ds28ea00/pd.py                      |    5 +-
 decoders/mdio/__init__.py                          |   39 +
 decoders/mdio/pd.py                                |  330 ++
 decoders/midi/__init__.py                          |    3 +-
 decoders/midi/lists.py                             |  699 ++-
 decoders/midi/pd.py                                |  575 +-
 decoders/mlx90614/__init__.py                      |    3 +-
 decoders/mlx90614/pd.py                            |    5 +-
 decoders/{dcf77 => modbus}/__init__.py             |   13 +-
 decoders/modbus/pd.py                              |  931 ++++
 decoders/{ir_nec => mrf24j40}/__init__.py          |    8 +-
 decoders/mrf24j40/lists.py                         |  166 +
 decoders/mrf24j40/pd.py                            |  134 +
 decoders/mx25lxx05d/pd.py                          |  375 --
 decoders/mxc6225xu/__init__.py                     |    3 +-
 decoders/mxc6225xu/pd.py                           |    8 +-
 decoders/{dcf77 => nrf24l01}/__init__.py           |   12 +-
 decoders/nrf24l01/pd.py                            |  329 ++
 decoders/nunchuk/__init__.py                       |    3 +-
 decoders/nunchuk/pd.py                             |   23 +-
 decoders/onewire_link/__init__.py                  |    3 +-
 decoders/onewire_link/pd.py                        |   87 +-
 decoders/onewire_network/__init__.py               |    3 +-
 decoders/onewire_network/pd.py                     |   20 +-
 decoders/pan1321/__init__.py                       |    3 +-
 decoders/pan1321/pd.py                             |    8 +-
 decoders/parallel/__init__.py                      |    3 +-
 decoders/parallel/pd.py                            |   20 +-
 decoders/{ir_nec => ps2}/__init__.py               |   12 +-
 decoders/ps2/pd.py                                 |  144 +
 decoders/{ir_nec => pwm}/__init__.py               |    7 +-
 decoders/pwm/pd.py                                 |  150 +
 decoders/{ir_nec => qi}/__init__.py                |    8 +-
 decoders/qi/pd.py                                  |  244 +
 decoders/{ir_nec => rfm12}/__init__.py             |    8 +-
 decoders/rfm12/pd.py                               |  494 ++
 decoders/rgb_led_spi/__init__.py                   |    3 +-
 decoders/rgb_led_spi/pd.py                         |   20 +-
 decoders/{dcf77 => rgb_led_ws281x}/__init__.py     |   12 +-
 decoders/rgb_led_ws281x/pd.py                      |  128 +
 decoders/rtc8564/__init__.py                       |    3 +-
 decoders/rtc8564/pd.py                             |   16 +-
 decoders/{tlc5620 => sdcard_sd}/__init__.py        |    7 +-
 decoders/sdcard_sd/lists.py                        |  185 +
 decoders/sdcard_sd/pd.py                           |  444 ++
 decoders/sdcard_spi/__init__.py                    |    3 +-
 decoders/sdcard_spi/pd.py                          |  107 +-
 decoders/{ir_nec => spdif}/__init__.py             |    8 +-
 decoders/spdif/pd.py                               |  257 +
 decoders/spi/__init__.py                           |    3 +-
 decoders/spi/pd.py                                 |   98 +-
 decoders/{mx25lxx05d => spiflash}/__init__.py      |   11 +-
 decoders/spiflash/lists.py                         |  112 +
 decoders/spiflash/pd.py                            |  485 ++
 decoders/{dcf77 => ssi32}/__init__.py              |   15 +-
 decoders/ssi32/pd.py                               |  124 +
 decoders/{rtc8564 => stepper_motor}/__init__.py    |    9 +-
 decoders/stepper_motor/pd.py                       |   97 +
 decoders/{dcf77 => swd}/__init__.py                |   17 +-
 decoders/swd/pd.py                                 |  349 ++
 decoders/{ir_nec => t55xx}/__init__.py             |    8 +-
 decoders/t55xx/pd.py                               |  331 ++
 decoders/{ir_nec => tca6408a}/__init__.py          |    8 +-
 decoders/tca6408a/pd.py                            |  129 +
 decoders/{tlc5620 => timing}/__init__.py           |    7 +-
 decoders/timing/pd.py                              |  123 +
 decoders/tlc5620/__init__.py                       |    3 +-
 decoders/tlc5620/pd.py                             |  127 +-
 decoders/uart/__init__.py                          |    3 +-
 decoders/uart/pd.py                                |  180 +-
 decoders/usb_packet/__init__.py                    |    3 +-
 decoders/usb_packet/pd.py                          |   79 +-
 .../{tlc5620 => usb_power_delivery}/__init__.py    |    5 +-
 decoders/usb_power_delivery/pd.py                  |  579 ++
 decoders/usb_request/__init__.py                   |   50 +
 decoders/usb_request/pd.py                         |  359 ++
 decoders/usb_signalling/__init__.py                |    3 +-
 decoders/usb_signalling/pd.py                      |  233 +-
 decoders/{dcf77 => wiegand}/__init__.py            |   11 +-
 decoders/wiegand/pd.py                             |  134 +
 decoders/xfp/__init__.py                           |    3 +-
 decoders/xfp/pd.py                                 |  179 +-
 decoders/z80/pd.py                                 |    2 +-
 error.c                                            |    1 +
 exception.c                                        |  168 +-
 instance.c                                         |  236 +-
 libsigrokdecode-internal.h                         |   73 +-
 libsigrokdecode.h                                  |   36 +-
 libsigrokdecode.pc.in                              |   15 +-
 log.c                                              |  134 +-
 {autostuff => m4}/libtool.m4                       | 2522 +++++----
 {autostuff => m4}/ltoptions.m4                     |  127 +-
 {autostuff => m4}/ltsugar.m4                       |    7 +-
 {autostuff => m4}/ltversion.m4                     |   12 +-
 {autostuff => m4}/lt~obsolete.m4                   |    7 +-
 m4/sigrok.m4                                       |  449 ++
 module_sigrokdecode.c                              |   69 +-
 session.c                                          |   60 +-
 srd.c                                              |   98 +-
 tests/{check_core.c => core.c}                     |   15 +-
 tests/{check_decoder.c => decoder.c}               |  163 +-
 tests/{check_inst.c => inst.c}                     |   25 +-
 tests/lib.h                                        |    3 +
 tests/{check_main.c => main.c}                     |   13 +-
 tests/runtc.c                                      |  837 ---
 tests/{check_session.c => session.c}               |   21 +-
 tools/install-decoders                             |   34 +-
 type_decoder.c                                     |  131 +-
 type_logic.c                                       |   38 +-
 util.c                                             |  265 +-
 version.c                                          |    1 +
 version.h                                          |   70 -
 version.h.in                                       |   16 +-
 206 files changed, 26160 insertions(+), 11216 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 39955af..c99f8d2 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,8 +1,2005 @@
-commit 788b2c6183554d8d985c2ab59cd1d5d3575009dd
+commit bc12b1a236fb45f23210f11004414fa9b8172b21
 Author: Uwe Hermann <uwe at hermann-uwe.de>
-Date:   Tue May 6 23:08:09 2014 +0200
+Date:   Mon Dec 26 23:17:59 2016 +0100
 
-    Doxyfile: Set version to 0.3.0.
+    configure.ac: Bump package version to 0.4.1.
+
+commit ca50668ea24eb8ace8c4e80a191b38faa338d628
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Dec 26 23:15:41 2016 +0100
+
+    configure.ac: Bump libtool/library version from 3:0:0 to 3:1:0.
+    
+    The libtool current:revision:age numbers change from 3:0:0 to 3:1:0.
+    
+    Details:
+    http://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info
+    
+    This changes the library filename (e.g. on Linux) from
+    libsigrokdecode.so.3.0.0 to libsigrokdecode.so.3.0.1, the SONAME
+    (+symlink) stays at libsigrokdecode.so.3, though.
+
+commit 25dedf929f200402e9e836da47c56048f8fe4d11
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Dec 26 23:14:31 2016 +0100
+
+    Doxyfile: Set version to 0.4.1.
+
+commit fe6910edcdcaadd1fa96757b8e2608660e6c0448
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Dec 26 23:09:26 2016 +0100
+
+    NEWS: Add list of user-visible changes so far.
+
+commit 043cb80cd557c075aef78c2d21aa39b9805adbbd
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Dec 26 23:28:58 2016 +0100
+
+    configure.ac: Also check for Python 3.6.
+
+commit c7bedf187faebd5376936e156c9339a558bb12e9
+Author: Gerhard Sittig <gerhard.sittig at gmx.net>
+Date:   Sun Nov 20 16:51:47 2016 +0100
+
+    build support: sort list of installed items, factor out pretty printer
+    
+    Alpha-sort the list of installed items, to support developers which scan
+    the list for newly added items. Factor out the logic which pretty prints
+    installed items while maintaining a maximum screen output line length.
+
+commit 205e6dbb202ad667eb2dff657d73db8a249dba82
+Author: Karl Palsson <karlp at etactica.com>
+Date:   Tue Nov 29 14:01:22 2016 +0000
+
+    valgrind: free channels
+    
+    Signed-off-by: Karl Palsson <karlp at etactica.com>
+
+commit 231bb99df32ae5453f08ad27f42d34126059cf4b
+Author: Karl Palsson <karlp at etactica.com>
+Date:   Fri Nov 25 13:55:56 2016 +0000
+
+    valgrind: safely iterate lists
+    
+    Old versions triggered valgrind errors as the API method to remove an
+    entry modifies the list that was being iterated.
+    
+    Signed-off-by: Karl Palsson <karlp at etactica.com>
+
+commit db8156ea94cea737a97bd721c3cb8b3922ef7098
+Author: Gerhard Sittig <gerhard.sittig at gmx.net>
+Date:   Sun Oct 16 18:25:29 2016 +0200
+
+    Print error messages when decoders fail load time checks
+    
+    Several checks get applied when loading externally provided protocol
+    decoders. Print error messages when checks fail, so that developers can
+    better resolve issues.
+    
+    The sequence of tests terminates upon the first failed check, while
+    decoders may suffer from several issues at the same time. This is
+    considered acceptable, as it reduces the commit's size and the code's
+    complexity. This commit only adds error messages, and does not change
+    logic/behaviour.
+    
+    Failed API version checks result in two messages: One specific message
+    which reflects the decoder's version and what's supported by the loader,
+    and a generic message that the API version check has failed. This is
+    done to simplify the logic of a rarely used error code path.
+    
+    This commit addresses libsigrokdecode Bug 704, and allows to identify
+    decoders from parallel installations of differing version.
+    
+    This fixes bug #704.
+    
+    Signed-off-by: Gerhard Sittig <gerhard.sittig at gmx.net>
+
+commit 7b62f75e9beb3da64c0f009740fe0156e0694adf
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 25 22:34:55 2016 +0200
+
+    srd_inst_decode(): Return SRD_ERR_ARG if unitsize is 0.
+
+commit 173f85e1072cc0ed2a1099efd7dae0b1023960f6
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 25 22:26:41 2016 +0200
+
+    srd_inst_decode(): Make the code API version dependent.
+
+commit 6ebb97f7aa2499db801610369df61c59b01c5611
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 25 22:22:07 2016 +0200
+
+    Factor out srd_decoder_apiver().
+
+commit 7b849244f6bc98e20281785b6b4842752e163e43
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 25 22:01:04 2016 +0200
+
+    srd_inst_decode(): Improve comments and log messages.
+    
+    Also, drop @since tag (as the function is not public).
+
+commit 5ac1f449d18c46d47293e061f2cda8ed54732224
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 25 21:57:39 2016 +0200
+
+    srd_session_send(): Improve Doxygen comments.
+
+commit 47509b17ad9aecd867de76210fb4130bbe78938e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue May 24 21:42:02 2016 +0200
+
+    Move common/ directory into decoders/.
+    
+    This simplifies cross-platform handling of the Python/decoder paths
+    and module installation/dist a bit and also fixes bug #804.
+
+commit 1a400317a8e6d2599216287814553059bed4d6c5
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Sat Oct 3 16:26:23 2015 +0200
+
+    Supply metadata to stacked decoders
+    
+    Currently only toplevel decoders receive the samplerate, thus stacked
+    decoders are not able to derive e.g. timestamps from the sample number.
+    
+    This fixes bug #664.
+
+commit 30d6d3ba0980ef9f41bc088263d416de0adcdb41
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Thu Apr 21 01:33:49 2016 +0200
+
+    Add common directory for shared modules.
+
+commit fa5f451084e3c11600395acdedb7c5cd4d4221a3
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Dec 26 22:20:08 2016 +0100
+
+    Backport current PDs from git mainline.
+
+commit 46fe9a4ab1327b03809fe3e5e288773f3f93e5ea
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Jan 29 23:36:58 2016 +0100
+
+    Doxyfile: Set version to 0.4.0.
+
+commit b144d63507bed89c551e3fdd74fe106c4d264fc2
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Jan 29 23:32:37 2016 +0100
+
+    Bump libtool version (not package version) to 3:0:0.
+    
+    The last release (0.3.0) had the libtool version (current:revision:age)
+    set to 2:0:0. Since this release removes and changes interfaces, the new
+    version is 3:0:0.
+    
+    http://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info
+    
+    This changes the library filename (e.g. on Linux) from
+    libsigrokdecode.so.2.0.0 to libsigrokdecode.so.3.0.0, the SONAME
+    (+symlink) becomes libsigrokdecode.so.3.
+
+commit a87daa42b8f9a223b6af4a1b693e4214fc802ff4
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Jan 29 21:25:18 2016 +0100
+
+    NEWS: Update for upcoming 0.4.0 release.
+
+commit 7bee21e85c0cc7ada8ce54b8ff0fa759d084a7c5
+Author: Martijn van Buul <martijn.van.buul at gmail.com>
+Date:   Tue Jan 26 22:13:26 2016 +0100
+
+    configure.ac: Also check for Python 3.5.
+    
+    This fixes bug #739.
+
+commit 96a044da40fd33e6f3273f0052fdd12f54770150
+Author: Daniel Thompson <daniel at redfelineninja.org.uk>
+Date:   Fri Jan 22 08:29:09 2016 +0000
+
+    uart: Optimize handling of samples when tx and rx are both idle
+    
+    Re-enable the fast path for identical samples but only when both
+    pins are waiting for the start bit. For sparse data sets (I tested
+    UT61E capture log) the optimization results in a >4x decode
+    improvement.
+
+commit 27c69645218c7cc88c991c8c18b585ffd092acc0
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Sun Jan 10 19:23:55 2016 +0200
+
+    arm_itm: Use objdump instead of addr2line.
+    
+    This improves speed and fixes bug 564. Code is somewhat
+    of a copypaste from the arm_etm counterpart, but there
+    are enough differences that it is easier to keep separate
+    copy of the objdump parsing in each.
+
+commit 669f30f4b1035a8eb0a5350246a3bc50cf8b376d
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 25 16:28:23 2015 +0100
+
+    usb_power_delivery: Raise SamplerateError instead of Exception.
+    
+    (for consistency with the other PDs)
+
+commit 2f37032807e19bc93b7f3223e1568db46318790c
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Dec 23 20:01:48 2015 +0100
+
+    Use self.out_binary naming consistently across all PDs.
+
+commit 2824e81140d3a8e37464f758cf67f50f2f7afca7
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Dec 23 20:00:45 2015 +0100
+
+    Use a Python list (not tuple) for OUT_BINARY.
+    
+    This is more consistent with annotation syntax and looks slightly
+    better in most cases.
+
+commit 0679f5bf9b2334deb75243abb80ef7e0d0472c18
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Dec 20 17:49:31 2015 +0100
+
+    Drop obsolete support for annotation tuples (only support lists).
+    
+    None of the PDs use this.
+
+commit 91ae892dcb8637961fc52cc8b528e1f77bec3a53
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 18 17:42:16 2015 +0100
+
+    em4100: Simplify the code a bit.
+
+commit 13090f246f88ecea35afd43e3ada0dda061f6994
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 18 17:29:10 2015 +0100
+
+    em4100: Use ss/es naming for consistency across PDs.
+
+commit 1a782fad8a1e8addeb1f27e221b286ffe2b2e30a
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 18 17:21:47 2015 +0100
+
+    em4100: Eliminate some unnecessary int()s.
+
+commit 428e40cb08410595126f245e5379cd3104747937
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 18 18:14:06 2015 +0100
+
+    em4100: Change annotation setup a bit, decode more protocol details.
+
+commit 8f26590799306bf7e13241c345adbf1fde811ec7
+Author: Benjamin Larsson <benjamin at southpole.se>
+Date:   Tue Dec 15 01:00:01 2015 +0100
+
+    Add RFID EM4100 protocol decoding
+
+commit 033e7d4db76f2e2a289d5567e9532f26201cfa74
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Dec 16 18:14:30 2015 +0100
+
+    usb_power_delivery: Use "if not self.samplerate" form.
+    
+    Use the "if not self.samplerate" form, which catches both the case
+    where self.samplerate is None, as well as the case where it is 0.
+    
+    This is also consistent with all the other PDs.
+
+commit 89b9aaf771abd5642dc8acb2281af3bb66a9424f
+Author: Vincent Palatin <vpalatin at chromium.org>
+Date:   Wed Nov 25 09:19:58 2015 -0800
+
+    usb_power_delivery: convert double quotes to single quotes
+    
+    For consistency with other decoders, convert all the double quotes around
+    strings to single quotes.
+    
+    Signed-off-by: Vincent Palatin <vpalatin at chromium.org>
+
+commit 45883c6b54839988850d5fb3d6fdbedab0011ced
+Author: Marcus Comstedt <marcus at mc.pp.se>
+Date:   Fri Dec 4 22:36:17 2015 +0100
+
+    init: Don't let Python override signal handlers
+    
+    This fixes bug #461.
+
+commit 502acfc2c71a2bbc97d4d7597150cd479bead1ee
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Dec 4 22:11:14 2015 +0100
+
+    usb*: Minor cosmetics.
+
+commit 1647db062c75b5058fbbd581438a25e76f17cde6
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Tue Dec 1 06:44:43 2015 +0100
+
+    usb_signalling: detect PREamble PID
+    
+    PID decoding is normally done in the packet layer, but the signalling
+    layer has to switch behaviour on detection of an PREamble PID.
+
+commit 9821622af021360a92334d1a6b465c8e3aab90b6
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Tue Dec 1 06:48:02 2015 +0100
+
+    usb_signalling: add signaling states needed after LS PREamble PID
+
+commit be0f8fee99fe939c50ed5d2483a924754788c0b3
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Tue Dec 1 05:53:32 2015 +0100
+
+    usb_{packet,request}: handle PREamble transmissions
+
+commit 831d893d4b9e4f76b5e645ee5e6fcfd4962ffa6a
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Mon Nov 30 00:35:11 2015 +0100
+
+    usb_signalling: fix SOP detection after an error condition
+    
+    If the oldsym is not set to 'J' before entering IDLE state, the SOP
+    detection will never trigger
+
+commit e655c0aa44ac56ff66ad98d30a97cf852bdf7048
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Mon Nov 30 00:00:03 2015 +0100
+
+    usb_packet: handle errors from usb_signalling
+    
+    If a packet had any errors, the usb_signalling PD will not send an EOP
+    but an ERR message. Wait for the next SOP in both cases.
+
+commit 72b2a50cc23388ba3568fc96deda79a7e39cbfc5
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Sun Nov 29 23:56:53 2015 +0100
+
+    usb_request: Handle transmission timeouts
+    
+    If a device or host did not receive a handshake 18 bit times after the
+    EOP, there was a transmission error and the host may repeat the
+    transmission
+
+commit 519092e31aa4f2288dd82d43719d5a88d4e465b9
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 07:15:36 2015 +0100
+
+    usb_signalling: add option to automatically set signalling speed
+    
+    In automatic mode, the bus is assumed to be in IDLE state. After a
+    RESET, the bus state is checked again.
+
+commit 13e813080ccf342e9577317400530335c5475764
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 05:39:10 2015 +0100
+
+    usb_signalling: decode RESET and Keep-Alive signalling conditions
+    
+    Resets are at least 10ms at the root hub downstream facing port and
+    2.5us at the device (root hub reset may be shortened by itermediate
+    hubs).
+    Keep-alive is a low-speed only signalling condition, as low-speed has no
+    SOFs to inhibit devices to enter suspend
+
+commit 6fbab493aaee26f9ecba0268261d1f3264339d9d
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 05:20:22 2015 +0100
+
+    usb_signalling: use explicit positions for packet start/end
+    
+    Instead of centering the block around the sampleposition, which shows
+    some visual glitches due to rounding, use the edge positions already
+    known. Remove unused halfbit symbol.
+
+commit 0f274b53a9c0c8a40cdb0ed41023705d99bc6c6c
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 04:55:56 2015 +0100
+
+    usb_signalling: handle symbol errors in EOP state
+    
+    Only SE0 and J are valid symbols during EOP
+
+commit bef4949d31076cf7dfdea5ed8bf7800bf3e2678d
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 04:52:53 2015 +0100
+
+    usb_signalling: remove unneeded syms array
+    
+    Do not call get_eop() from get_bit(), but directly issue the symbol. As
+    get_eop() is only called during the GET EOP state, the SE0 is implicit and
+    there is no need to save it into the syms array.
+
+commit ce780be23a64df70ac350c8584d484e72c00990e
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 04:20:54 2015 +0100
+
+    usb_signalling: remove unused ss_sop member
+
+commit 033d6221f3d0cd607bb11031a2764a293bf4bff1
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 04:11:37 2015 +0100
+
+    usb_signalling: detect bit stuffing errors
+    
+    More than six consecutive 1's are an error
+
+commit 56cc44ff1106e8e28d9242b6232552c501090ed4
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Fri Nov 13 04:05:24 2015 +0100
+
+    usb_signalling: consolidate symbol output
+    
+    No need to replicate the symbol formatting in several places
+
+commit 8c90d7bdf21f091bb8bf6a45fbb8602e406b10e4
+Author: Paul "LeoNerd" Evans <leonerd at leonerd.org.uk>
+Date:   Sun Nov 8 00:49:08 2015 +0000
+
+    spi: Add a 'TRANSFER' output type.
+
+commit 92a06d0b6bbe173257d7c76ed2318f5b35f65637
+Author: Paul "LeoNerd" Evans <leonerd at leonerd.org.uk>
+Date:   Sat Nov 7 23:39:59 2015 +0000
+
+    Fix documentation comment in SPI decoder
+
+commit 79065c6f7602f1f02399bcf45bb3ef0cb73587ae
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Nov 21 20:18:47 2015 +0100
+
+    usb_power_delivery: Minor typo and whitespace fixes.
+
+commit fddb311472d4458382418de3f091bd1b997d3a89
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Nov 21 19:35:15 2015 +0100
+
+    usb_power_delivery: Use the same license header format as other PDs.
+
+commit ced6589fc96e49c0fa69565c46e5cb4fb25459bc
+Author: Vincent Palatin <vpalatin at chromium.org>
+Date:   Thu May 29 06:51:13 2014 -0700
+
+    USB Power Delivery protocol decoder
+    
+    Decode and packetize the Biphase Mark Coding (aka differential Manchester)
+    as used in the Universal Serial Bus Power Delivery Specification Revision 2.0
+    v1.1, then decode the packet content.
+    
+    Signed-off-by: Vincent Palatin <vpalatin at chromium.org>
+
+commit a1497fa349673fb5cd2cb5b62dbc90160d7f9e49
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Nov 21 18:43:06 2015 +0100
+
+    spiflash: Fix incorrect 'inputs' field.
+    
+    (this PD is indeed stacked on top of SPI)
+
+commit 979d5dd08f33e90da58ef6bb76137693ed84693a
+Author: Paul "LeoNerd" Evans <leonerd at leonerd.org.uk>
+Date:   Tue Nov 3 14:02:11 2015 +0000
+
+    Initial attempt at MAX7219/MAX7221 decoder
+
+commit c63f5a875761cb83abfad7ede0615415cdc90c76
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Nov 3 02:12:49 2015 +0100
+
+    srd_decoder_unload(): Remove PD from the internal list.
+    
+    This issue was discovered via the newly added unit tests.
+
+commit 1b6f39e39b9700a787db81268c4ae9cd0d3f1499
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Nov 3 02:12:29 2015 +0100
+
+    tests/decoder.c: Add some srd_decoder_unload*() tests.
+
+commit 76a4498f3a1eb0ce3919c3ce72fad76f99049942
+Author: Elrond <elrond+sigrok.org at samba-tng.org>
+Date:   Wed Oct 21 16:17:19 2015 +0200
+
+    UART: Handle framing errors better
+    
+    1. Show Frame Error on the Start bit
+    2. Don't overwrite framing errors with (valid) start/stop bit info
+
+commit 943f9176255c63924fcf55c6ba8bad05e91d4923
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Oct 6 22:42:52 2015 +0200
+
+    exception: Decorate catch function with format attribute
+
+commit 41d43a33fb4088889aba931cbdbc032263a6f397
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Oct 6 21:08:36 2015 +0200
+
+    build: Require GLib 2.28.0
+    
+    This is needed for e.g. g_slist_free_full(), which incidentally
+    has been in use for a while already.
+
+commit e9dd2fea0514df9316a12bae191b810811fc9f01
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Oct 6 22:30:14 2015 +0200
+
+    util: Factor out Python module load
+    
+    Create a utility function for loading a Python module by its name
+    in UTF-8.
+
+commit 6d67d057d13318deb0a11de2589b5442df389092
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Oct 6 21:07:47 2015 +0200
+
+    decoder: Refactor loading code and plug leaks
+
+commit 201a85a8ea071d37f4fda2668c0a1c488d852f4e
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Mon Oct 5 01:53:43 2015 +0200
+
+    Python: Restrict code to stable ABI subset
+    
+    Limit usage of the Python C API to the stable ABI subset as defined
+    by PEP 384. This removes some type definitions and functions which
+    libsigrokdecode made use of. Convert all affected code to suitable
+    API alternatives. Also fix a few leaks that became apparent while
+    working on the code.
+    
+    The most visible change is that PyTypeObject is now an opaque type.
+    Thus, the custom Decoder and srd_logic types are now created on the
+    heap via an alternative API. Unfortunately, since tp_name is now
+    inaccessible, type names had to be removed from the log output.
+    
+    Stack traces after Python exceptions are now formatted by calling
+    into Python, since the trace object C API is no longer available.
+
+commit bd0e7d2e71e7a05b2bb0686a86a75b8fcb92fd54
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Sun Oct 4 00:43:38 2015 +0200
+
+    usb_request: USB transaction decoder and PCAP generator
+    
+    The new decoder stacks on top of the usb_packet PD. It adds one new
+    annotation row, and is able to save the decoded data as PCAP trace.
+    
+    It has been successfully tested against all traces in sigrok-dumps and
+    some more traces.
+
+commit 91a19cb31778ccb6db79c4d4d75d993d974ebae0
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Oct 6 08:29:56 2015 +0200
+
+    usb_packet: Document CRC5 ERROR and CRC16 ERROR packets.
+
+commit 64b45b207121eeb9b0db7f71ba067f23fe7f7ea7
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Oct 6 08:28:03 2015 +0200
+
+    usb_{signalling,packet}: Minor cosmetics.
+
+commit a241cfb6e1fbf1f7c85109a54e914672b633f5f3
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Wed Sep 30 00:24:24 2015 +0200
+
+    usb_signalling: Track USB symbol width to compensate frequency errors
+    
+    USB low/full speed allows for frequency tolerance of 1.5%/0.25%. At
+    maximum packet size (sync + PID + data + CRC16) of 12 bytes/1027 bytes
+    this amounts to 1.4 bits/20 bits, so the decoder has to lock to the
+    actual symbol frequency to avoid any symbol misdetections.
+    
+    The signal is sampled twice, once at the symbol center and once at
+    the expected edge position. Comparing the symbol at both positions gives
+    an indication if the current bit width is too low or too high. Adjust
+    accordingly.
+
+commit 0e3cb15e814f20b201709688ab4eaa6eee54dc40
+Author: Stefan Brüns <stefan.bruens at rwth-aachen.de>
+Date:   Thu Oct 1 00:12:29 2015 +0200
+
+    usb_packet: calculate and check CRC5/CRC16
+    
+    In case CRC validation fails, an crc5-err/crc16-err annotation is issued,
+    instead of crc5-ok/crc16-ok, and the error is noted in the annotation
+    text.
+
+commit d9673085e0f35f4cf7704f340ce56f954d7beab6
+Author: Roland Hieber <rohieb at rohieb.name>
+Date:   Sun Oct 4 23:04:02 2015 +0200
+
+    rfm12: fix small typo
+    
+    There is a small typo in the rfm12 protocol decoder that I just noticed:
+
+commit b480383d4605915f7b4cd8f14ccf62af9bf710f3
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sat Oct 3 14:28:43 2015 +0200
+
+    tests: Do not reference parent directory in includes
+    
+    Rely on the compiler include path instead.
+
+commit 41bab68212533f4697ad378af574e06ea83e4fd9
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sat Oct 3 14:21:01 2015 +0200
+
+    tests: Rename DECODERS_DIR to DECODERS_TESTDIR
+    
+    Avoid confusion resulting from using the same macro name for
+    different purposes.
+
+commit 583001b3f16795abd24278fbb2e5232a7ca27fb0
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sat Oct 3 14:17:07 2015 +0200
+
+    build: Do not hard-code decoders location on Windows
+
+commit 40c6ac1d3fbded276dcbff23e8bc099896ab2fb5
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sat Oct 3 13:18:09 2015 +0200
+
+    init: Also look for decoders in XDG data directories
+
+commit d8d409590ce21116d85800c0eb8be287817a0eed
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sat Oct 3 11:40:33 2015 +0200
+
+    init: Simplify srd_decoder_searchpath_add()
+    
+    Don't mess with colon-separated search path strings -- instead,
+    simply prepend items to the sys.path list object. Also keep the
+    internal decoder path list in the same order as the items added
+    to sys.path.
+
+commit 750e122d2bcdf05e600112ffda431f97608db387
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Sep 15 11:42:05 2015 +0200
+
+    jitter, pwm: Avoid Unicode string literals
+    
+    It seems the Python we ship along our Windows binaries does not
+    support u"..." strings, even though it's been a language feature
+    since Python 2. Remove the "u" prefix to avoid a syntax error.
+    
+    Also, consistently use format "%.1f" at all scales.
+    
+    This fixes bug #569.
+
+commit 544038d90e05c03f6f914c7771ee52dd85784ca8
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 14 19:05:54 2015 +0200
+
+    can: Improve stuff bit annotation placement.
+
+commit d4a28d0fb6e1380590564be2b47ba3642130555b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 14 18:25:02 2015 +0200
+
+    can: Emit bit value annotations.
+
+commit c6bfbc0043089e006c684bcce609da50aadded81
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 14 17:56:46 2015 +0200
+
+    Makefile.am: Shorten ChangeLog target a bit.
+
+commit ef3a66299ade1bc41090d0b6d24c21b6bcfad571
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 23:05:42 2015 +0200
+
+    log: Use GLib printf for consistency
+    
+    Just as in libsigrok, use g_vfprintf() in the log callback to make
+    sure we are linking to a standard-conforming printf implementation.
+
+commit fdfc532ecd49fc3353627ef4a093366e73d6b91a
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 22:10:54 2015 +0200
+
+    Build: Move _POSIX_C_SOURCE definition to config.h
+    
+    Do not redefine it though when already set, so that it can be
+    overridden by the user, or indirectly by the compiler settings.
+
+commit 367843620d039ad183bc4d7c33d91c316d717621
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 22:07:11 2015 +0200
+
+    Build: Include <config.h> first in all source files
+    
+    Since Autoconf places some important feature flags only into the
+    configuration header, it is necessary to include it globally to
+    guarantee a consistent build.
+
+commit 4916b17368e8ed06f4bfd045052ab0f891c33954
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 22:01:34 2015 +0200
+
+    Fix srd_log() format warnings
+
+commit fd4918101e0878be9d399a344511253f5867a646
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 21:32:27 2015 +0200
+
+    log: Enable varargs format warnings
+    
+    Decorate srd_log() with the GCC format printf attribute so that the
+    compiler can check the format string and arguments for consistency.
+    
+    Also remove the srd_err(), sr_warn(), etc. functions and replace
+    them with macro wrappers around srd_log().
+
+commit 9fb7e7fe2c7edafdeedf1976d1723ffe557c8a7c
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 13 21:10:40 2015 +0200
+
+    log: Remove srd_log_logdomain_{get,set} from the API
+    
+    The confusingly named srd_log_logdomain_set() simply set a global
+    string prefixed to the log message by the default log callback.
+    This is pretty much useless, misleadingly named, and not used by
+    either sigrok-cli or PulseView.
+
+commit 2730fe2397101f2c0a66abd3a7fd5fa531d3c710
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Sep 10 18:19:47 2015 +0200
+
+    instance.c: Don't use 'di' before NULL-checking it.
+
+commit 9576e005e18b2d0131e0fce5279a401cbe71c0f8
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Thu Sep 10 18:45:50 2015 +0200
+
+    Build: Put --no-print-directory into GNUMAKEFLAGS
+    
+    Also output the compiler version in the configuration summary.
+
+commit 0fd8a35de8b89fce395c14190f63c02b9aa976df
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Thu Sep 10 18:44:55 2015 +0200
+
+    sigrok.m4: Update with latest version from libsigrok
+
+commit a6c1c359dab0f707ecdc0bf7fcb7de9b7dabfd06
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 6 10:53:54 2015 +0200
+
+    libsigrokdecode.pc: Publish decodersdir variable
+    
+    This is so that downstream modules can find the install location
+    of the decoders.
+
+commit a4b5d9a99e4d202ccd65bc77624949e68a858e3a
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Sun Sep 6 10:51:22 2015 +0200
+
+    Build: Show CC and CFLAGS in configuration summary
+
+commit e4bafb8df34c2c051ec7a2e9a5e50b54849f0eb2
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Sep 3 09:19:56 2015 +0200
+
+    jtag_stm32: Decode IDCODE contents as strings (not just hex vals).
+
+commit d011c2e1fe2e4f0144a2c8e56d7feeda8520fd81
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Sep 3 08:36:21 2015 +0200
+
+    jtag_stm32: Decode more fields, improve IDCODE handling.
+
+commit 0edb5d58301af36844681f6427b06040678f63d0
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Sep 2 21:06:01 2015 +0200
+
+    jtag_stm32: Cleanups, shorter code.
+
+commit a4dd548f5332453cef7442e453eef99343bdc5fb
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Sep 2 20:49:47 2015 +0200
+
+    jtag_stm32: Update to reflect change in jtag OUT_PYTHON.
+
+commit 36faa6d0a353709235b7bf1076ae29552154e4a9
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Sep 2 20:49:20 2015 +0200
+
+    jtag: Submit bit samplenumbers together with the bits.
+
+commit 6cdc1e0997c41ef92bb39a67f5f67b676ee5205e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Sep 1 20:13:27 2015 +0200
+
+    jtag_stm32: Fix incorrect handling of registers.
+    
+    The STM32F10xxx has two serially connected JTAG TAPs, the boundary scan tap
+    (5 bits) and the Cortex-M3 TAP (4 bits). See UM 31.5 "STM32F10xxx JTAG TAP
+    connection" for details.
+    Due to this, we need to ignore the last bit of each data shift (and we
+    currently ignore the 5 bits of the boundary scan tap).
+
+commit 80214a11ba67e76257750e2dae3b1169c3e61c17
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Aug 16 00:37:34 2015 +0200
+
+    jtag: Add more annotations, fix a SHIFT-IR/-DR issue.
+    
+    The code was previously not decoding a bit for the first state change
+    to SHIFT-IR/-DR, which was incorrect.
+
+commit f7332ee0869cea37577257126acfe40bbe9f4db4
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 14 20:05:34 2015 +0200
+
+    jtag: Fix/enable OUT_PYTHON output.
+
+commit 27b3f2b09722ac0333657212f1c5592ca6f4fe56
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 28 19:25:09 2015 +0200
+
+    Replace another -D_DEFAULT_SOURCE with -D_POSIX_C_SOURCE=200112L.
+
+commit 94ac149f168731a96e5b9adc2addaceb9b170142
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 28 18:34:34 2015 +0200
+
+    Build: Go back to _POSIX_C_SOURCE=200112L
+
+commit 3a2086f011619dc62c58f39ffcfade9763813276
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Wed Aug 26 23:12:28 2015 +0200
+
+    configure: Enable largefile support on 32-bit systems
+
+commit 7614222ca6cc73aae478d0ed659c0bcedfee4cc3
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Wed Aug 26 14:07:39 2015 +0200
+
+    Build: Define feature test macro _DEFAULT_SOURCE
+    
+    This basically makes glibc expose the same set of features as
+    if gcc was invoked without any restricting -std=c* option. Unlike
+    _GNU_SOURCE however, it does not enable GNU-specific extensions.
+    
+    So, with this macro defined the behavior of Linux with glibc
+    should match that of other platforms.
+
+commit a654ef6e407f1f914a6ec9b104a5e4cf9b84524c
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Wed Aug 26 13:01:16 2015 +0200
+
+    Build: Use TESTS prefix instead of CHECK for flag variables
+    
+    In order to avoid confusion of the flags-gathering pkg-config
+    result with the actual test for the availability of "check",
+    change the pkg-config output variable prefix from CHECK to TESTS.
+
+commit 051d71c2b2851a3bcee29f46f7c7027a2edbc568
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Aug 25 03:06:33 2015 +0200
+
+    Clean up .gitignore
+
+commit 7eb90f2304e10d13281d47d944168fe40a77e6d6
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Tue Aug 25 02:59:48 2015 +0200
+
+    Build: Adopt new Autotools magic
+
+commit bcd4e47e8cc688d2a04c6fbfde1e0a354405f769
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Mon Aug 24 21:09:47 2015 +0200
+
+    Build: Reduce autogen.sh to trivial stub
+    
+    Use autoreconf instead of invoking the various Auto tools
+    separately. Get rid of the Darwin-specific guesswork -- it does
+    not make sense to handle this at the level of libsigrokdecode.
+    
+    People should set up their ACLOCAL_PATH themselves as appropriate
+    for their own system; just as they already need to set up various
+    other paths.
+
+commit 28aeef67d01b0263934feb3147813d3c750f942c
+Author: Daniel Elstner <daniel.kitta at gmail.com>
+Date:   Mon Aug 24 21:07:42 2015 +0200
+
+    Build: Add copy of libsigrok Autoconf macro file
+
+commit aac0ac249169a8774b30a2f3458a056ae2c80c63
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 21 14:50:04 2015 +0200
+
+    nunchuk: Fix inverted button press logic.
+    
+    The buttons are pressed if the respective bit is 0.
+
+commit cda2d36cfeed3f921252ffa95377529d6bdc074b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 20 19:36:12 2015 +0200
+
+    Pass unitsize per sample chunk.
+    
+    Don't pass unitsize to srd_inst_channel_set_all(), have that only
+    set the channel map. Instead, srd_session_send() now has a parameter
+    for the unitsize which is passed with every new chunk to be decoded.
+    
+    This is in preparation to fix issues with devices or files which
+    have a unitsize != 1 and where the "guessed" unitsize based on the
+    number of channels is not correct.
+    
+    This also allows for (potential) future changes where every chunk can
+    indeed have a different unitsize.
+    
+    This fixes (parts of) bug #352.
+
+commit bbe1b715a71536e38a2b7e2362dbd8827a18ec1f
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Aug 18 08:24:29 2015 +0200
+
+    mrf24j40: Fix a register address typo.
+
+commit 04c310c8d90a29dc4125ad2b707d08ed4fe15c52
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 17 22:04:46 2015 +0200
+
+    tlc5620: Add options for per-DAC Vref, show voltages.
+    
+    Instead of showing raw values in the annotations, calculate the
+    actual voltage (based on raw value, gain, and Vref) and use that.
+
+commit a945c53611b3c8bdfd5d30fec7675320213acfe0
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 17 22:05:06 2015 +0200
+
+    tlc5620: Handle the case of less than 11 bits in a command.
+
+commit 3992b1e180283036ad4a834419b73d5d3eb53089
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 17 22:01:37 2015 +0200
+
+    tlc5620: Properly handle LOAD and LDAC based operations.
+    
+    - If LOAD goes low *and* LDAC is already low, the voltage is set
+      immediately.
+    
+    - If LOAD goes low but LDAC is high, the value is only written into
+      an internal register, but the voltage is not changed (yet).
+    
+    - If LDAC goes low, all four DAC voltages (DAC A/B/C/D) are set
+      according to the respective register values at the same time.
+
+commit e57813d5b3a44d0e504b6571c9b06a8a8da79f8a
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 17 21:46:22 2015 +0200
+
+    tlc5620: Only decode the last 11 bits, ignore the rest.
+
+commit ce0c47f34659181a7c5f82bfb782d8a5f5987ac7
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 17 21:28:21 2015 +0200
+
+    tlc5620: Fix incorrect DAC selection decode, add more annotations.
+
+commit 3e84c443857ae649be31df7ca13690c6d3578e54
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 14 19:01:39 2015 +0200
+
+    usb_packet: Handle invalid packets more gracefully.
+    
+    Previously the PD was blindly trying to decode any packet, no matter
+    whether it was too short (and/or bogus) or not, causing issues like this:
+    
+      srd: Calling usb_packet decode(): IndexError: list index out of range
+    
+    Such cases of invalid input are now handled better by emitting "UNKNOWN"
+    and "Invalid packet" annotations.
+    
+    This fixes bug #186.
+
+commit 42227c2d29c8330c955cf64cf92be0bf1bf4aeeb
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 14 13:48:08 2015 +0200
+
+    usb_packet: Fix incorrect DATA*/MDATA handling.
+    
+    Thanks to Pavel Sukortsev for the bug report and fix.
+    
+    This fixes bug #623.
+
+commit 08c41387ca016a59c041c8bc76efab037da5894a
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 6 19:27:04 2015 +0200
+
+    Add initial SD card (SD mode) decoder.
+    
+    In the current state the decoder can decode the following commands:
+    CMD0, CMD2, CMD3, CMD6, CMD7, CMD8, CMD9, CMD10, CMD13, CMD16, CMD55,
+    ACMD6, ACMD13, ACMD41, ACMD51.
+    
+    Other commands (and more details for existing commands) will be added later.
+
+commit fbff319f0a65e2d87a609f77a32b26ef200a5215
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Jul 23 17:12:41 2015 +0200
+
+    Slightly more verbose logging in srd_inst_decode().
+
+commit f7504c3772512586c3178e26b6945a4064c070d7
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Jul 18 18:04:08 2015 +0200
+
+    Bump version to 0.4.0 (the upcoming next major release).
+
+commit 709b84383503326eba654613d083352b00d31c97
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Jul 18 17:59:19 2015 +0200
+
+    Append "-git" to the version string.
+    
+    This avoids confusion with the released tarballs.
+
+commit db858a048288645d00eeb643dc43006ef9875280
+Author: Bart de Waal <bart at waalamo.com>
+Date:   Mon Jul 13 23:59:55 2015 +0200
+
+    Add protocol decoder for Modbus RTU.
+
+commit d574715e3916740deeffbd7637d20c78e062fff3
+Author: Josef Gajdusek <atx at atx.name>
+Date:   Thu Jul 9 12:54:28 2015 +0200
+
+    qi: Add Qi charger protocol decoder
+
+commit e4302cbe5cb375a50bd9a30a8a2855d9fa6ab14d
+Author: Aurelien Jacobs <aurel at gnuage.org>
+Date:   Sat Jun 6 22:05:06 2015 +0200
+
+    Add an MDIO/SMI decoder.
+
+commit 295b78c7d971e1abd7021d88415523ad66a3e448
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Jul 1 01:21:53 2015 +0200
+
+    adns5020: Minor tweak to annotation format.
+
+commit 07505b2a1a31759f90f9e7e2bfee5d75d4b1b729
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Jul 1 00:59:23 2015 +0200
+
+    mrf24j40: Factor out register lists to lists.py.
+
+commit fecabafe31aa77e039268b63fa6a409922858505
+Author: Karl Palsson <karlp at tweak.net.au>
+Date:   Wed May 27 01:25:16 2015 +0000
+
+    Add a Microchip MRF24J40 802.15.4 2.4GHz RF tranceiver decoder.
+    
+    No interpretation of register bits, nor attempting to decode packet contents,
+    but all shifted register addresses and long register memory regions are
+    decoded.
+    
+    Signed-off-by: Karl Palsson <karlp at tweak.net.au>
+
+commit 8f7f170ffbb0acfd170054546a9ecf27f557167e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Jun 22 15:15:17 2015 +0200
+
+    adns5020: Add manufacturer name to description.
+
+commit ef0734978955d34e42187f79f6c2ed910b4b873d
+Author: Karl Palsson <karlp at tweak.net.au>
+Date:   Sat May 16 17:14:50 2015 +0000
+
+    Add Avago ADNS-5020 optical mouse sensor decoder.
+    
+    Decodes reads/writes of registers. Understands resetting on chip select if
+    provided. Does not understand burst mode.
+    
+    Signed-off-by: Karl Palsson <karlp at tweak.net.au>
+
+commit e2ba53bbd8d176aedc8f5f9a3bb4086bc5f526f3
+Author: Karl Palsson <karlp at tweak.net.au>
+Date:   Sat May 30 20:28:55 2015 +0000
+
+    am23xx: explicitly mention RHTxx devices.
+    
+    Include their compatibility in the dropdown options too.
+
+commit 468c974e7bdbc068ad1771069e3e0adb35853ad5
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Apr 26 17:53:24 2015 +0200
+
+    timing: Shorten annotations (time units).
+
+commit 92adde514e1be3015ebd44da813fb6bec0001370
+Author: Baruch Even <baruch at ev-en.org>
+Date:   Sat Apr 4 21:21:34 2015 +0200
+
+    Add a decoder that calculates timings between transitions.
+
+commit c2446117b9758b14e328e4244e9787e5fb65f62b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Apr 4 20:41:24 2015 +0200
+
+    spiflash: Add lists.py and a 'chips' PD option.
+
+commit 3ca1f1b3530ff5fb2e93785516e088a58429191e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Apr 4 19:41:44 2015 +0200
+
+    Rename the 'mx25lxx05d' PD to 'spiflash'.
+    
+    This is in preparation of making the PD more generic so it can support
+    a lot more xx25 series SPI (NOR) flash chips.
+
+commit 868fd207a7506ae2ab48d6a8755350e452d60521
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Apr 4 18:34:42 2015 +0200
+
+    Fix a bunch of typos.
+
+commit c357abd198bd195cb9ea015130dc76c8c7a33651
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Apr 7 02:36:47 2015 +0200
+
+    autogen.sh: Drop obsolete MinGW/MSYS items.
+    
+    For Windows builds (which require MinGW-w64) we currently support:
+    
+     - cross-builds using MXE (mxe.cc) and possibly other cross-compile setups
+    
+     - native builds using MSYS2 (sf.net/projects/msys2/)
+    
+    Neither of those require explicitly specifying ACLOCAL_DIR.
+
+commit 3085037bbcb7f6a5ea101227f3ab2045645a21c4
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Apr 3 23:21:59 2015 +0200
+
+    onewire_link: Fix a bug when the samplerate is too low for the PD.
+    
+    The code was trying to emit annotations before
+    self.register(srd.OUTPUT_ANN) was run.
+    
+    This fixes bug #357.
+
+commit 348118b732231daf9d9e4b3f7c80e7939f3eb0ca
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Apr 3 22:50:41 2015 +0200
+
+    Makefile.am: Use libtool's -no-undefined option.
+
+commit cdceaa9438e889e55d7f5c364f05548afba66bc3
+Author: Andreas Sandberg <andreas at sandberg.pp.se>
+Date:   Fri Feb 13 21:42:01 2015 +0000
+
+    spi: Don't decode data lines if CS isn't asserted
+    
+    Avoid decoding and outputting data from the SPI bus if the CS pin
+    hasn't been asserted. This avoids confusing both users and stacked
+    decoders which otherwise end up seeing traffic intended for other
+    chips (or just noise).
+    
+    Note: The old behavior of decoding all traffic is still in place if
+    no CS pin has been wired up to the decoder.
+    
+    This fixes bug #559.
+
+commit a7c8dc5e3a2b7ad38eb03a958180f97f3059ea31
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Apr 2 22:48:03 2015 +0200
+
+    Slightly shorten a few PD descriptions.
+
+commit d2bcb32bc16eddffc9ec54b505c03028a2ec4160
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Sat Mar 7 16:14:19 2015 +0200
+
+    Add a decoder for stepper motor direction/speed signals.
+
+commit 1c023fab6542d33b3e1c7f32504c0fcc9495dfb1
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Sat Mar 7 15:55:18 2015 +0200
+
+    Fix a few decoding bugs with arm_etmv3.
+    
+    Fixed:
+    - wrong address decoding for some branches
+    - error in annotation lists for exception entry/exit
+    - exception was being thrown for 0E0N p-header packets
+    - fixes to objdump output parsing, better function name & source code matching
+    
+    New features:
+    - added decoding of IRQ names for branch exception info
+    - added support for -C option to objdump to decode C++ symbol names
+    - put branches on the "Exceptions" annotation row when they contain exception info.
+
+commit e4227bafd63472d1a0d23fa54f62a2b20e296115
+Author: Matt Porter <mporter at konsulko.com>
+Date:   Mon Mar 30 23:59:38 2015 -0400
+
+    pwm: add period annotation
+
+commit 077fa8acbcb8b585af6f5323f16221940a27a72e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Mar 7 19:12:15 2015 +0100
+
+    Use g_malloc*() consistently, simplify error handling.
+    
+    Use g_malloc*() for small allocations and assume they always
+    succeed. Simplify error handling in a few places accordingly.
+    
+    Document the rules in the README file.
+
+commit c052046717c09758bbdf62819e0029dddcae7159
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Feb 28 14:18:56 2015 +0100
+
+    unit tests: Drop unneeded check_ filename prefix.
+
+commit 7c139a54d14979f832c53d6f7fae7d415ca41a74
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Mar 25 09:41:23 2015 +0100
+
+    mx25lxx05d: Implement FAST READ command.
+
+commit 1483fb220ce56405433aee298d1637f6b041ac2b
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Mon Feb 23 19:47:56 2015 +0200
+
+    Fix typo in swd decoder
+
+commit 686f0c3621cd8ef7264f3e45e0218f2ebdfb612a
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Mon Feb 23 19:49:06 2015 +0200
+
+    Add ARM TPIU/ITM/ETMv3 decoders
+
+commit 5dc48752efc84171dece2dcef93577e5483b9775
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Feb 24 21:46:04 2015 +0100
+
+    nrf24l01: Change 'xn297_extensions' option to 'chip'.
+    
+    This allows for easily extending the PD to support other clones or
+    compatibles of the nRF24L01(+) chip as well.
+
+commit b03e2209d5e83e3c1b9737097b13109c7e4658c3
+Author: Mike <mike at flomp.net>
+Date:   Fri Feb 6 16:42:32 2015 +0000
+
+    nrf24l01: Add option to support the XN297's extra registers
+
+commit b5712ccbbcd023e5ac20d790bf75af3c18fc66d5
+Author: Petteri Aimonen <jpa at git.mail.kapsi.fi>
+Date:   Sun Feb 15 19:08:36 2015 +0200
+
+    Improve uart decoder sample positions at high data rates.
+    
+    At 3 samples per bit, the uart decoder took the value at the last sample
+    instead of the middle one. Improve calculations so that sampling is more
+    accurate at odd number of samples per bit.
+
+commit 2590c098bb44f660a9668db66deaf59f3a7a651b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Jan 31 23:39:02 2015 +0100
+
+    unit tests: Disable timeout for one of the test cases.
+    
+    This one can take a while, thus disable the timeout.
+
+commit 9177963de41c2d003d417049470eea3c98eeb2ef
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Jan 24 20:46:18 2015 +0100
+
+    README: Update build requirements list.
+
+commit c4d5221077ef95488325dd104a806eadb5b5f13b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Nov 19 18:57:56 2014 +0100
+
+    Add 24xx I2C EEPROM protocol decoder.
+
+commit 49d0e05ce73b2b8e47714b5d95e66e9b27aeaa4d
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Dec 28 14:33:50 2014 +0100
+
+    spi: Add binary output facilities for MISO/MOSI.
+    
+    This fixes bug #424.
+
+commit be42cffca100c00d0d5510b08dcb66655f8a5746
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Dec 16 14:51:47 2014 +0100
+
+    edid: Add annotation rows.
+
+commit 2ef800662842775738659e72ade594713cfb849b
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Dec 16 14:51:19 2014 +0100
+
+    eded: Add all sections.
+
+commit 70aa53ec10dabe4a5267e142974b35d1312f7119
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Nov 23 23:06:45 2014 +0100
+
+    jitter: Simplify ascii-float binary out.
+    
+    This also outputs one item of OUT_BINARY per jitter value (not one
+    item per ASCII character in the ASCII floating point number).
+
+commit 05aaa48637fe56ac087569d784dbfdc91341f619
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Nov 23 22:55:54 2014 +0100
+
+    jitter: Rename "jitter" binary out to "ascii-float".
+
+commit 5f987d6f312a7a586b0af5aca267b98747e5df4a
+Author: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+Date:   Thu Nov 13 15:50:43 2014 -0500
+
+    jitter: add a binary output to report the raw jitter value.
+    
+    Signed-off-by: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+
+commit 961699aaab1e44dab827c9f1884100b87a0a97fd
+Author: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+Date:   Wed Nov 12 12:42:03 2014 -0500
+
+    jitter: fixes an error when a miss clock/signal is detected
+    
+    Signed-off-by: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+
+commit 34cfd419098c5a9dc32270308c5e55e9c6893e91
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Nov 9 20:29:31 2014 +0100
+
+    jitter: Factor out handle_clk() and handle_sig().
+
+commit c2049e2c98e3186a2c6462e5dcede8d2b0747021
+Author: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+Date:   Thu Oct 23 13:08:29 2014 -0400
+
+    Add a timing jitter decoder.
+    
+    Signed-off-by: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+
+commit 9658c7100a62499cce1939193c8be80bb300d0f8
+Author: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+Date:   Wed Oct 29 23:31:43 2014 -0400
+
+    pwm: Fix and rework
+    
+    Reworked in the algorithm:
+     - Fixed the polarity setting
+     - Taken in consideration the first transition
+     - Using the 'None' state instead of -1 and 0 value
+     - Simplify the algorithm and remove useless branches and variables
+     - Avoid re-calculating the same thing more than once
+     - Renamed a few variables for a better understanding
+     - Duty cycle precision changed to floating value
+    
+    Otherwise:
+     - Added a meta OUTPUT for the duty cycle average
+     - Renamed the polarity option:
+            'polarity', 'active low/high' are well-understood terms.
+     - Added comments
+    
+    Signed-off-by: Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+
+commit 8a110ab1ea46d89d36a610e4249fe1eabed27757
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Sun Oct 19 22:54:51 2014 +0200
+
+    spi: Use 'None' to signal the missing CS# pin.
+
+commit 22630a3d54361f083877a68724e8b823d5e063a7
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Sun Oct 19 21:29:07 2014 +0200
+
+    nrf24l01: Don't decode incomplete commands.
+    
+    Wait for the CS# line to be inactive before decoding the commands.
+
+commit 3cc4c4a96dba8390ec4eabbd62cc1d50d653640e
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Sun Oct 19 20:39:38 2014 +0200
+
+    nrf24l01: Check for CS# pin and only throw exceptions once.
+
+commit 1c49e875623918f8893308307f487a1f551daec4
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Sat Oct 18 11:31:16 2014 +0200
+
+    spi: Tell stacked decoders about missing CS# signal.
+    
+    This could previously be detected by the absence of a CS-CHANGE packet
+    before the first data packet, but it makes the stacked decoder simpler
+    if it is told directly.
+
+commit b4332f0fdd7706d9caf39a5dcd8a1b5b06a626ab
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Oct 16 21:23:19 2014 +0200
+
+    Add a PWM decoder.
+
+commit 0c7d5a56449babeb84013118935c0dacecdadd70
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Oct 16 17:58:28 2014 +0200
+
+    uart: Fix code comment.
+
+commit 7cf698c5475ac6948d7a9d5c2a6e4ec9cb878d84
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Oct 16 09:35:27 2014 +0200
+
+    uart: Emit databyte and bits list at the same time.
+    
+    This will allow for much simpler code in stacked PDs.
+    
+    Adapt stacked PDs to new API.
+
+commit bd6594c0cdae0a525e147c6e33e496ff87823d16
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Oct 15 15:23:22 2014 +0200
+
+    instance.c: Fix whitespace.
+
+commit ee7de90f6e61d15e4aeb40ccbe1a6d007b1fc9a1
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Oct 15 15:22:48 2014 +0200
+
+    midi: Fix two incorrect sample numbers.
+
+commit 486b19ce017c6663be6574dacd0c823304903bca
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Oct 13 17:05:07 2014 +0200
+
+    All PDs: More consistent names for ss/es variables.
+    
+    Use self.ss/self.es, or if there's a need to differentiate
+    them a bit more, use self.ss_<suffix>/self.es_<suffix> consistently.
+    
+    Also, drop some unused variables.
+
+commit 95d11271b46a46788d497481d03177e883c8554e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Oct 1 19:01:39 2014 +0200
+
+    All PDs: Only import the 'Decoder' object.
+    
+    Anything else in the pd.py files doesn't have to be imported/exposed.
+
+commit 0b6bc7f9554c0980153563b6a3d16c3642fc4651
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 20:21:33 2014 +0200
+
+    am230x: Factor out handle_byte() to simplify state machine.
+
+commit dcfb60a1658243c3130774fe00645e7fedb23211
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 19:02:00 2014 +0200
+
+    swd: Drop unnecessary debug code.
+
+commit 4afe40462af650a0df1bfb7bd185ee666f2b30f0
+Author: Angus Gratton <gus at projectgus.com>
+Date:   Sat Jul 12 19:34:19 2014 +1000
+
+    swd: Add SWD protocol decoder for ARM Serial Wire Debug format.
+    
+    Supports annotated output for analysing debug sessions, Python output
+    for potential stacked decoders looking at higher level debug
+    operations.
+
+commit 25adf5cf29d26751d3f481bd2d22fe8d034ed44c
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 17:31:40 2014 +0200
+
+    am230x: Minor documentation fix.
+
+commit ed758f091ebb31380868041da87812d3e4ea4a94
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 15:13:50 2014 +0200
+
+    am230x: Use slightly more liberal timing values.
+    
+    This seems to be required at least for some AM2301 and DHT11 sensors.
+
+commit cda1352a7ce0248e6db1996d9ddb9dbee2f91e8b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 14:58:25 2014 +0200
+
+    am230x: Change option to 'device' to allow for more devices.
+
+commit f87162978a3f804d43ae12208c3d6a4a86382c1c
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 14:57:56 2014 +0200
+
+    am230x: Fix self.reset() method name.
+
+commit 47405f47db235c06d9f2ad26ae51791136b62a91
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Oct 12 14:31:21 2014 +0200
+
+    am230x: Minor cosmetics.
+
+commit b1f2b85bd9a7cb79265f251cbecba84cdc04dd5e
+Author: Johannes Römer <jroemer at physik.uni-wuerzburg.de>
+Date:   Mon Oct 6 23:30:22 2014 +0200
+
+    Add decoder for AM230x digital humidity and temperature sensors.
+
+commit 280d554c29fc234d27be77d602436395d01da6dd
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 28 22:48:39 2014 +0200
+
+    Replace ann_format with ann_class.
+    
+    The naming has been changed to "annotation class" a while ago.
+
+commit e228150a0e8d60ef3fcaa6f077305a8e6045dfe8
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 28 21:38:39 2014 +0200
+
+    sdcard_spi/usb_packet: Drop unused variables.
+
+commit 4eafeeefc716a617837f1d69c040753b0b8d71f7
+Author: David Barksdale <amatus at amatus.name>
+Date:   Mon Sep 15 11:50:09 2014 -0500
+
+    uart: Implement signal inversion
+
+commit f38da319741c74b83b4d2146f872d05cbd8e2f3c
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Sep 11 00:45:08 2014 +0200
+
+    Fix out-of-tree build of the unit tests.
+
+commit cb9a5046bed65e38b28c21afcb8945b19d4e8012
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Sep 10 09:26:11 2014 +0200
+
+    Various PDs: Whitespace, cosmetics.
+
+commit cac173dbec2b1761414ace8289204945557c8526
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 8 21:44:03 2014 +0200
+
+    rfm12: Cosmetics.
+    
+    Also, update author email address.
+
+commit c9021bc926a42284baf99c174eba4a52b412847e
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 8 11:55:07 2014 +0200
+
+    rfm12: Frequencies: Fix typo (915MHz), add 315MHz entry.
+
+commit 04ff49263b0a462250d2301e6d4d17db5904a8d3
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 8 11:54:25 2014 +0200
+
+    rfm12: Avoid using the Python 'range' keyword as variable.
+
+commit 4ef0ff313b3ac48d585f581593738c1a3e607f26
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 8 11:48:05 2014 +0200
+
+    rfm12: Drop debug printing.
+    
+    Any errors during decoding should be handled by the PD state machine.
+
+commit d44c802b7cd5a89fee9cdf294acb999d30dd2507
+Author: Sławek Piotrowski <slawomir.piotrowski at payu.pl>
+Date:   Thu Sep 4 00:32:14 2014 +0200
+
+    RFM12 decoder
+
+commit c414f1996bec719dda64ca5731fea78f1d48887a
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Sep 1 17:38:09 2014 +0200
+
+    PD tests moved into the sigrok-test repo.
+    
+    Drop them from the libsigrokdecode repository.
+
+commit 586361052b414d9e17fdecf54c5db0282c25339f
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 30 00:55:56 2014 +0200
+
+    spdif: Simplify get_pulse_type() a bit.
+
+commit 5302d1e99ed4234b622e7d85ff3e58e2e4648f25
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 30 00:16:33 2014 +0200
+
+    spdif: Use strings for decoder states.
+
+commit cc16130e89911cae694c5245df9fd223750c47d3
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 30 00:09:50 2014 +0200
+
+    spdif: Add another annotation helper.
+
+commit eb148e7a78ed4c3b9615b41d9c967cb5f403fa0f
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Fri Aug 29 23:50:56 2014 +0200
+
+    spdif: Refactor and reduce nesting level.
+
+commit cb6d4c6d8a06ee62a6aa37cc5cddc71cd5ae3adb
+Author: Guenther Wenninger <robin at bitschubbser.org>
+Date:   Sat Apr 19 02:20:42 2014 +0200
+
+    Add initial S/PDIF decoder.
+
+commit 00bdc23e73fc3af5a7656ae584216330e4a31556
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 21:35:26 2014 +0200
+
+    ds1307: Warn about (and ignore) non-DS1307 traffic.
+
+commit 7d74799011f28796bbb8165dc3bcd4c8cca12052
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 21:19:05 2014 +0200
+
+    ds1307: Correctly handle address wrap-around.
+
+commit 53908ef10d1c5e3d77c3551703fa1633303b9242
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 21:17:32 2014 +0200
+
+    ds1307: Refactoring and cleanups.
+
+commit 903e9b14c84400579e0d786b7a96e9e587b5849b
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 21:03:00 2014 +0200
+
+    ds1307: Handle SRAM register accesses.
+
+commit 37834eed4b104fcf77258cca846302911dea34ca
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 20:45:56 2014 +0200
+
+    ds1307: Handle register 0x07 (control register).
+
+commit 5188abb910323c22c57ef95880cdd78eaab2e1f8
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 20:36:09 2014 +0200
+
+    ds1307: Emit per-bit annotations for registers.
+    
+    Also, add more annotation classes (and annotation rows).
+
+commit 11bd6317ec8d00b3a421516c2e9747a8f7a551ea
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 18:43:51 2014 +0200
+
+    configure.ac: Use AM_CFLAGS instead of CFLAGS.
+    
+    CFLAGS, CPPFLAGS, LDFLAGS and so on are so-called "user variables" and
+    are meant for users of the package to use/override. The package itself
+    should not set or modify them in any way. Instead, the "shadow variables"
+    such as AM_CFLAGS, AM_CPPFLAGS, AM_LDFLAGS and so on, can be modified by
+    the package.
+
+commit 98c47d1107c0f0509cb7e40f2805286e1319afef
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sat Aug 16 18:38:07 2014 +0200
+
+    tca6408a: Cosmetics.
+
+commit d4026957a57e5f665fa91c8d706976613e29c1b4
+Author: alberink <alberink at stampfini.org>
+Date:   Thu Jun 19 17:18:52 2014 +0200
+
+    Add decoder for TCA6408A I2C I/O expanders.
+
+commit 28c3c217cc70cf2eba41dbca2954c5d8382802d7
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 14 19:30:54 2014 +0200
+
+    tests: Factor out srdtest_setup() / srdtest_teardown().
+
+commit d841d5b26f2134143fc80c9898522d13387b7cc8
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Aug 14 18:51:11 2014 +0200
+
+    Whitespace and consistency fixes.
+
+commit dfbe1fb2a602114f74cc4f7e3610204dbb559012
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 11 22:53:02 2014 +0200
+
+    pdtests: Check for SamplerateError in all PDs that emit it.
+
+commit a573d3944c410d90adb5130323e0f3792d9ae201
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Mon Aug 11 22:53:35 2014 +0200
+
+    parallel: Enforce that at least one pin must be provided.
+
+commit f04964c696336f5699a099bbd64785f199d91f4c
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Aug 10 09:22:29 2014 +0200
+
+    spi/nrf24l01/uart: Use ChannelError exception.
+    
+    Rename the old MissingDataError to the clearer ChannelError. Also, add
+    ChannelError in the UART decoder.
+
+commit 8aeedf9ee376f1b48fe9c42924ebf34f9c8c2ddd
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Sun Aug 3 23:30:42 2014 +0200
+
+    nrf24l01: prettify annotation output
+
+commit 1f6f2ad8c33e58cfd40ea0370e6d2dfbd6040026
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Jul 31 00:44:20 2014 +0200
+
+    tests/pdtest: Small fix to make it work with Python 3.2.
+    
+    Python 3.2 doesn't yet have the copy() method for lists:
+    
+      AttributeError: 'list' object has no attribute 'copy'
+
+commit 83df730dd21ce52670a593455cfe5e732989a90d
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Thu Jul 31 00:02:22 2014 +0200
+
+    tests/check_session.c: Fix compiler warning.
+    
+    This fixes 'warning: "_POSIX_C_SOURCE" redefined' with some Python
+    versions.
+
+commit 3b884e8567e7a5fc2f5582951ec9af9a69fd8b65
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Jul 23 00:00:33 2014 +0200
+
+    Drop references to obsolete sigrok-commits mailing list.
+
+commit 7149b578a48e90a8b34d70174f8c3ce51de1e282
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Jul 20 13:16:30 2014 +0200
+
+    runtc: Update to the new libsigrok session API.
+    
+    (also fixes the build for libsigrokdecode)
+
+commit 3a1501e9e07a93a9b157fcce53aa070c5a0bf3d8
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Sun Jul 20 11:31:27 2014 +0200
+
+    Fix incorrect doxygen comment for srd_decoder_list().
+    
+    This fixes bug #378.
+
+commit 35b380b1156434b73d4a976c68f5ab3604c8510a
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Jul 15 22:49:43 2014 +0200
+
+    All PDs: Minor whitespace and consistency fixes.
+    
+     - No newlines at the end of files.
+     - No trailing ';' characters.
+     - Comparison with None: Use 'is None' or 'is not None'.
+     - Comparison with True/False: Use 'if cond:' or 'if not cond:'.
+     - Various minor whitespace fixes.
+
+commit 22fc7ace72f3165c98208a8f544156e04a709639
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Wed Jul 9 17:31:32 2014 +0200
+
+    uart/i2cfilter: Don't check multiple-choice options.
+    
+    For options which only have a limited set of valid values, we don't need
+    to check (in the PD) whether a valid value was supplied, since the backend
+    can do that for us.
+
+commit 21b39043472eeeb2e0155eafc73247f5010af714
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Jul 8 21:36:53 2014 +0200
+
+    Various PDs: Minor consistency fixes.
+    
+    (Consistently use single-quotes for all Python strings everywhere)
+
+commit 21cda9512f29947617da45822ab524b1f76f56c1
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Jul 8 21:32:32 2014 +0200
+
+    Various PDs: Throw SamplerateError instead of Exception.
+    
+    Also, use the "if not self.samplerate" form, which catches both the case
+    where self.samplerate is None, as well as the case where it is 0.
+
+commit e28f7aee3b96afeb543e0c3c29e3950ddd61a490
+Author: Uwe Hermann <uwe at hermann-uwe.de>
+Date:   Tue Jul 8 21:21:03 2014 +0200
+
+    All PDs: Drop unneeded exceptions.
+    
+    In all current PDs it is not necessary to raise an exception upon
+    invalid states (of the PD's state machine), since we can guarantee that
+    no such invalid state can ever be reached in these PDs.
+
+commit 0e501c70cf26f208d7e523b7fe737d0e8d565109
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Tue Jul 8 22:15:30 2014 +0200
+
+    Add nRF24L01(+) protocol decoder.
+
+commit 34929ee00c976842196ca95240b6cb1a7f5d8c75
+Author: Jens Steinhauser <jens.steinhauser at gmail.com>
+Date:   Tue Jul 8 17:48:56 2014 +0200
+
+    spi: Fix order of MISO/MOSI data items.
+
+commit 0d06305deb8d94dfddfef710004a500bf30fb1ff
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Jul 8 21:43:58 2014 +0200
+
+    pdtest: Use new exception output.
+
+commit 84d7ecb947a8a6453fc0cb1d7973a821615dec54
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Jul 8 21:43:33 2014 +0200
+
+    Make exception output more predictable.
+
+commit f6c7eade2b8853b3d525b5cc0402e89ca74c1908
+Author: Marcus Comstedt <marcus at mc.pp.se>
+Date:   Tue Jul 1 00:07:40 2014 +0200
+
+    Remove dependency on Python.h from public API header
+    
+    This prevents Python.h from being included into client code, where
+    it can mess things up by e.g. redefining _POSIX_C_SOURCE.
+
+commit 67ecff568264e0af2cf137af1d0f4edf7a9dcf2e
+Author: Marcus Comstedt <marcus at mc.pp.se>
+Date:   Sun Jun 29 11:38:50 2014 +0200
+
+    runtc: Fix incorrect include directive
+    
+    runtc.c used to try to include "../config.h".  This only works when
+    building in the source tree, otherwise there is no config.h in the
+    parent directory of runtc.c.  However, the explicit path is
+    unnecessary since the build directory (whether the same as the source
+    directory or not) will always be added to the include path.
+
+commit 6a0341595610c9d14d4121bb8fa82ab7eeb03693
+Author: Marcus Comstedt <marcus at mc.pp.se>
+Date:   Mon Jul 7 01:36:22 2014 +0200
+
+    srd_decoder_load_all_path: Support zipimport paths
+    
+    srd_decoder_load() works perfectly with decoders stored inside zip files.
+    However, srd_decoder_load_all{_path,}() did not, because it assumed that
+    normal directory listings can be used to enumerate decoders, which is not
+    the case for zipped decoders.  Fix this by providing a fallback based on
+    the zipimporter Python class.
+
+commit 37b0da68d021530012f17e86b4754d109977ba76
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Fri Jun 27 18:45:46 2014 +0200
+
+    spi: Add coverage tests for all exceptions.
+
+commit 7ea7c017c334ebb466923f6e9fef9ef72e157676
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Fri Jun 27 18:45:01 2014 +0200
+
+    spi: Add coverage tests for all mosi/miso and lsb/msb combinations.
+
+commit 4fecc5a4bcb036f40e23ab967579334076203c2f
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Fri Jun 27 18:37:58 2014 +0200
+
+    spi: Refactor for more coverage, and remove dead code.
+
+commit 5f22c187f99ea13e0a1a5c8c995e73a75f93a9b1
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Thu Jun 26 19:56:02 2014 +0200
+
+    runtc: PD option value is a GVariant, not string.
+    
+    This is still broken: it needs to properly check the expected type of
+    the option, not just blindly assume G_VARIANT_TYPE_STRING.
+
+commit 604eece9928adbf4fb6b85470ceadeca1b73fabb
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Jun 24 18:17:22 2014 +0200
+
+    pdtest: Generate report regardless of verbose mode.
+
+commit 66a6eee7b0783f816187e75324df09a729a4070e
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Jun 24 16:04:45 2014 +0200
+
+    edid: Add another test, covering more code in the PD.
+
+commit d45058e87e7045fef1b7c4425de1917a554545f7
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Tue Jun 24 15:49:05 2014 +0200
+
+    pdtest: Generate a report listing missed lines across the whole PD.
+
+commit d2bdb1303679b97c3de5ce2d2d1f2b62c9828a3a
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Mon Jun 23 19:52:45 2014 +0200
+
+    i2c: Generate proper exception for missing samplerate, and test for it.
+    
+    Also remove some dead code.
+
+commit d510f7b3d5d03c6fca5b6af4e184dc2f46da9a1a
+Author: Bert Vermeulen <bert at biot.com>
+Date:   Mon Jun 23 19:49:47 2014 +0200
+
+    pdtest/runtc: Support for output type 'exception'.
+    
+    The match value should be the name of the exception thrown, e.g.
+    AttributeError, IndexError or even a custom exception defined in
+    the protocol decoder, such as SamplerateError.
+
+commit 4e891b94cae1b3e83155721476137a900fe242a6
+Author: Mike Frysinger <vapier at gentoo.org>
+Date:   Sat Jun 14 01:54:11 2014 -0400
+
+    do not add check to common cflags/libs
+    
+    Only the unittests use these flags, so don't go linking them in for
+    the main library too.
+
+commit 3b776f38b9fe2903fd7a4af9d9ca9edd159cea0b
+Author: Mike Frysinger <vapier at gentoo.org>
+Date:   Sat Jun 14 01:54:10 2014 -0400
+
+    fix test operator
+    
+    The == operator is not in POSIX.
+
+commit 4f8e40458fe9c0da90ba4634d248d4edb9f4b5aa
+Author: Kumar Abhishek <abhishek at theembeddedkitchen.net>
+Date:   Sat May 10 04:32:06 2014 +0700
+
+    runtc.c: Fix compiler warning
+    
+    c was of type char, while getopt returns an int. This
+    caused a compiler warning during build.
+
+commit 783b54337242e5c40da8ffc0fc18babbcd09bc67
+Author: Kumar Abhishek <abhishek at theembeddedkitchen.net>
+Date:   Sat May 10 04:32:05 2014 +0700
+
+    libsigrokdecode: Fix make -j issue with build_runtc
+    
+    The build of runtc caused issues with make -j as runtc
+    was attempted to be linked with libsigrokdecode before
+    libsigrokdecode was linked. Using LDADD to insert
+    libsigrokdecode ensures that it links before runtc,
+    ensuring the build completes correctly.
+
+commit 888bbe38a50a1e3224dcef68686a00e2754e8b47
+Author: Abhishek Kumar <abhishek at theembeddedkitchen.net>
+Date:   Fri May 9 06:05:00 2014 +0700
+
+    Add python as a pkg-config dependency
+    
+    The current libsigrokdecode build passes the python
+    CPPFLAGS and LDFLAGS directly into libsigrokdecode.pc.in.
+    This leads to issues while cross-compiling as while using
+    PKG_CONFIG_SYSROOT_DIR, there is a chance of the prefix
+    being duplicated. We now, while detecting the installation
+    of python (cross or normal), add a dependency for the
+    module name in the pkgconfig file (from configure.ac).
 
 commit 95e2b2f92b144e1b0edf29819a8585dbbc00f169
 Author: Uwe Hermann <uwe at hermann-uwe.de>
@@ -1185,19 +3182,19 @@ Date:   Sat Jan 18 19:15:41 2014 +0100
     Old sigrok-cli example usage:
     
      $ sigrok-cli -i 2ch-16bit-16khz.sr \
-    	-P i2s:sck=0:ws=1:sd=2,i2s_dump:filename=foo.wav
+            -P i2s:sck=0:ws=1:sd=2,i2s_dump:filename=foo.wav
      $ aplay foo.wav
     
     New sigrok-cli example usage:
     
      $ sigrok-cli -i 2ch-16bit-16khz.sr \
-    	-P i2s:sck=0:ws=1:sd=2 -B i2s=wav > foo.wav
+            -P i2s:sck=0:ws=1:sd=2 -B i2s=wav > foo.wav
      $ aplay foo.wav
     
     New sigrok-cli example usage (piping into other applications):
     
      $ sigrok-cli -i 2ch-16bit-16khz.sr \
-    	-P i2s:sck=0:ws=1:sd=2 -B i2s=wav | aplay -
+            -P i2s:sck=0:ws=1:sd=2 -B i2s=wav | aplay -
 
 commit e8ce01860673214bae97a6b793a7f55e13128dba
 Author: Uwe Hermann <uwe at hermann-uwe.de>
@@ -1606,8 +3603,8 @@ Date:   Wed Nov 27 16:47:04 2013 +0100
     file called 'config' can be created in that protocol decoder's
     directory, with the following content:
     
-    	# comments are ok
-    	extra-install vendorlist.txt commands.txt
+            # comments are ok
+            extra-install vendorlist.txt commands.txt
 
 commit 37b94c205e4c1c43e77e29993108f23066cbce05
 Author: Bert Vermeulen <bert at biot.com>
diff --git a/Doxyfile b/Doxyfile
index c86834c..629bc0e 100644
--- a/Doxyfile
+++ b/Doxyfile
@@ -38,7 +38,7 @@ PROJECT_NAME           = "libsigrokdecode"
 # could be handy for archiving the generated documentation or if some version
 # control system is used.
 
-PROJECT_NUMBER         = "0.3.0"
+PROJECT_NUMBER         = "0.4.1"
 
 # Using the PROJECT_BRIEF tag one can provide an optional one line description
 # for a project that appears at the top of each page and should give viewer a
diff --git a/HACKING b/HACKING
index a9a6a03..6aaedac 100644
--- a/HACKING
+++ b/HACKING
@@ -38,18 +38,21 @@ Random notes
  - Generally avoid assigning values to variables at declaration time,
    especially so for complex and/or run-time dependent values.
 
- - Consistently use g_try_malloc() / g_try_malloc0(). Do not use standard
+ - Consistently use g_*malloc() / g_*malloc0(). Do not use standard
    malloc()/calloc() if it can be avoided (sometimes other libs such
    as libftdi can return malloc()'d memory, for example).
 
  - Always properly match allocations with the proper *free() functions. If
-   glib's g_try_malloc()/g_try_malloc0() was used, use g_free() to free the
+   glib's g_*malloc()/g_*malloc0() was used, use g_free() to free the
    memory. Otherwise use standard free(). Never use the wrong function!
 
- - Never use g_malloc() or g_malloc0(). These functions do not return NULL
-   if not enough memory is available but rather lead to an exit() or segfault
-   instead. This behaviour is not acceptable for libraries.
-   Use g_try_malloc()/g_try_malloc0() instead and check the return value.
+ - We assume that "small" memory allocations (< 1MB) will always succeed.
+   Thus, it's fine to use g_malloc() or g_malloc0() for allocations of
+   simple/small structs and such (instead of using g_try_malloc()), and
+   there's no need to check the return value.
+
+   Do use g_try_malloc() or g_try_malloc0() for large (>= 1MB) allocations
+   and check the return value.
 
  - You should never print any messages (neither to stdout nor stderr nor
    elsewhere) "manually" via e.g. printf() or g_log() or similar functions.
@@ -182,9 +185,8 @@ You can run the libsigrokdecode testsuite using:
 Protocol decoder test framework
 -------------------------------
 
-You can run the protocol decoder tests using (e.g.):
-
- $ ./tests/pdtest -r -a -v
+Please see the sigrok-test repository for a protocol decoder test suite that
+checks the decoded data of various PDs against known-good reference data.
 
 
 Release engineering
diff --git a/Makefile.am b/Makefile.am
index 5c88cc4..a8df8f6 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -18,7 +18,20 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-ACLOCAL_AMFLAGS = -I autostuff
+ACLOCAL_AMFLAGS = -I m4
+AM_LIBTOOLFLAGS = --silent
+GNUMAKEFLAGS = --no-print-directory
+
+DECODERS_DIR = $(pkgdatadir)/decoders
+# Do not hard-code the decoders location on Windows.
+if WIN32
+AM_CPPFLAGS =
+else
+AM_CPPFLAGS = -DDECODERS_DIR='"$(DECODERS_DIR)"'
+endif
+
+# The tests CFLAGS are a superset of the libsigrokdecode CFLAGS.
+AM_CFLAGS = $(SRD_EXTRA_CFLAGS) $(SRD_WFLAGS) $(TESTS_CFLAGS)
 
 lib_LTLIBRARIES = libsigrokdecode.la
 
@@ -36,12 +49,11 @@ libsigrokdecode_la_SOURCES = \
 	error.c \
 	version.c
 
-libsigrokdecode_la_CPPFLAGS = $(CPPFLAGS_PYTHON) \
-	-DDECODERS_DIR='"$(DECODERS_DIR)"'
-libsigrokdecode_la_LDFLAGS = $(SRD_LIB_LDFLAGS) $(LDFLAGS_PYTHON)
+libsigrokdecode_la_LIBADD = $(SRD_EXTRA_LIBS) $(LIBSIGROKDECODE_LIBS)
+libsigrokdecode_la_LDFLAGS = -version-info $(SRD_LIB_VERSION) -no-undefined
 
-library_includedir = $(includedir)/libsigrokdecode
-library_include_HEADERS = libsigrokdecode.h version.h
+pkginclude_HEADERS = libsigrokdecode.h
+nodist_pkginclude_HEADERS = version.h
 noinst_HEADERS = libsigrokdecode-internal.h
 
 pkgconfigdir = $(libdir)/pkgconfig
@@ -50,35 +62,28 @@ pkgconfig_DATA = libsigrokdecode.pc
 EXTRA_DIST = Doxyfile HACKING contrib/sigrok-logo-notext.png
 
 if HAVE_CHECK
-TESTS = tests/check_main
+TESTS = tests/main
 check_PROGRAMS = ${TESTS}
-tests_check_main_SOURCES = \
+endif
+
+tests_main_SOURCES = \
 	libsigrokdecode.h \
 	tests/lib.h \
-	tests/check_main.c \
-	tests/check_core.c \
-	tests/check_decoder.c \
-	tests/check_inst.c \
-	tests/check_session.c
-tests_check_main_CFLAGS = @check_CFLAGS@
-tests_check_main_LDADD = $(top_builddir)/libsigrokdecode.la @check_LIBS@
-tests_check_main_CPPFLAGS = $(CPPFLAGS_PYTHON) \
-	-DDECODERS_DIR='"$(abs_top_builddir)/decoders"'
-endif
+	tests/main.c \
+	tests/core.c \
+	tests/decoder.c \
+	tests/inst.c \
+	tests/session.c
 
-if BUILD_RUNTC
-noinst_PROGRAMS = tests/runtc
-tests_runtc_SOURCES = tests/runtc.c
-tests_runtc_CPPFLAGS = $(CPPFLAGS_PYTHON) $(LIBSIGROK_CFLAGS) \
-	-DDECODERS_DIR='"$(abs_top_builddir)/decoders"'
-tests_runtc_LDFLAGS = -L$(top_builddir) $(LIBSIGROK_LIBS) $(LDFLAGS_PYTHON) -lsigrokdecode
-endif
+tests_main_CPPFLAGS = -DDECODERS_TESTDIR='"$(abs_top_srcdir)/decoders"'
+tests_main_LDADD = libsigrokdecode.la $(SRD_EXTRA_LIBS) $(TESTS_LIBS)
 
 MAINTAINERCLEANFILES = ChangeLog
 
-.PHONY: ChangeLog
+.PHONY: ChangeLog install-decoders
+
 ChangeLog:
-	git --git-dir $(top_srcdir)/.git log > ChangeLog || touch ChangeLog
+	git --git-dir '$(top_srcdir)/.git' log >$@ || touch $@
 
 dist-hook: ChangeLog
 	$(MKDIR_P) $(distdir)/tools
diff --git a/Makefile.in b/Makefile.in
index a32e9dd..9cbc4f6 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,7 +1,7 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
+# Makefile.in generated by automake 1.15 from Makefile.am.
 # @configure_input@
 
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
+# Copyright (C) 1994-2014 Free Software Foundation, Inc.
 
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -16,9 +16,18 @@
 
 
 
-
 VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
+am__is_gnu_make = { \
+  if test -z '$(MAKELEVEL)'; then \
+    false; \
+  elif test -n '$(MAKE_HOST)'; then \
+    true; \
+  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
+    true; \
+  else \
+    false; \
+  fi; \
+}
 am__make_running_with_option = \
   case $${target_option-} in \
       ?) ;; \
@@ -81,40 +90,24 @@ PRE_UNINSTALL = :
 POST_UNINSTALL = :
 build_triplet = @build@
 host_triplet = @host@
- at HAVE_CHECK_TRUE@TESTS = tests/check_main$(EXEEXT)
+ at HAVE_CHECK_TRUE@TESTS = tests/main$(EXEEXT)
 @HAVE_CHECK_TRUE at check_PROGRAMS = $(am__EXEEXT_1)
- at BUILD_RUNTC_TRUE@noinst_PROGRAMS = tests/runtc$(EXEEXT)
 subdir = .
-DIST_COMMON = INSTALL NEWS README AUTHORS ChangeLog \
-	$(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/configure $(am__configure_deps) \
-	$(srcdir)/config.h.in $(srcdir)/version.h.in \
-	$(srcdir)/libsigrokdecode.pc.in \
-	$(top_srcdir)/autostuff/depcomp $(library_include_HEADERS) \
-	$(noinst_HEADERS) $(top_srcdir)/autostuff/test-driver COPYING \
-	autostuff/ar-lib autostuff/compile autostuff/config.guess \
-	autostuff/config.sub autostuff/depcomp autostuff/install-sh \
-	autostuff/missing autostuff/ltmain.sh \
-	$(top_srcdir)/autostuff/ar-lib $(top_srcdir)/autostuff/compile \
-	$(top_srcdir)/autostuff/config.guess \
-	$(top_srcdir)/autostuff/config.sub \
-	$(top_srcdir)/autostuff/install-sh \
-	$(top_srcdir)/autostuff/ltmain.sh \
-	$(top_srcdir)/autostuff/missing
 ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/autostuff/libtool.m4 \
-	$(top_srcdir)/autostuff/ltoptions.m4 \
-	$(top_srcdir)/autostuff/ltsugar.m4 \
-	$(top_srcdir)/autostuff/ltversion.m4 \
-	$(top_srcdir)/autostuff/lt~obsolete.m4 \
-	$(top_srcdir)/configure.ac
+am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
+	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
+	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
+	$(top_srcdir)/m4/sigrok.m4 $(top_srcdir)/configure.ac
 am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
+DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \
+	$(am__configure_deps) $(noinst_HEADERS) $(pkginclude_HEADERS) \
+	$(am__DIST_COMMON)
 am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
  configure.lineno config.status.lineno
 mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = config.h
-CONFIG_CLEAN_FILES = version.h libsigrokdecode.pc
+CONFIG_HEADER = config.h version.h
+CONFIG_CLEAN_FILES = libsigrokdecode.pc
 CONFIG_CLEAN_VPATH_FILES =
 am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj = case $$p in \
@@ -144,17 +137,14 @@ am__uninstall_files_from_dir = { \
          $(am__cd) "$$dir" && rm -f $$files; }; \
   }
 am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgconfigdir)" \
-	"$(DESTDIR)$(library_includedir)"
+	"$(DESTDIR)$(pkgincludedir)" "$(DESTDIR)$(pkgincludedir)"
 LTLIBRARIES = $(lib_LTLIBRARIES)
-libsigrokdecode_la_LIBADD =
-am_libsigrokdecode_la_OBJECTS = libsigrokdecode_la-srd.lo \
-	libsigrokdecode_la-session.lo libsigrokdecode_la-decoder.lo \
-	libsigrokdecode_la-instance.lo libsigrokdecode_la-log.lo \
-	libsigrokdecode_la-util.lo libsigrokdecode_la-exception.lo \
-	libsigrokdecode_la-module_sigrokdecode.lo \
-	libsigrokdecode_la-type_decoder.lo \
-	libsigrokdecode_la-type_logic.lo libsigrokdecode_la-error.lo \
-	libsigrokdecode_la-version.lo
+am__DEPENDENCIES_1 =
+libsigrokdecode_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+am_libsigrokdecode_la_OBJECTS = srd.lo session.lo decoder.lo \
+	instance.lo log.lo util.lo exception.lo module_sigrokdecode.lo \
+	type_decoder.lo type_logic.lo error.lo version.lo
 libsigrokdecode_la_OBJECTS = $(am_libsigrokdecode_la_OBJECTS)
 AM_V_lt = $(am__v_lt_ at AM_V@)
 am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
@@ -164,33 +154,16 @@ libsigrokdecode_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
 	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
 	$(AM_CFLAGS) $(CFLAGS) $(libsigrokdecode_la_LDFLAGS) \
 	$(LDFLAGS) -o $@
- at HAVE_CHECK_TRUE@am__EXEEXT_1 = tests/check_main$(EXEEXT)
-PROGRAMS = $(noinst_PROGRAMS)
-am__tests_check_main_SOURCES_DIST = libsigrokdecode.h tests/lib.h \
-	tests/check_main.c tests/check_core.c tests/check_decoder.c \
-	tests/check_inst.c tests/check_session.c
+ at HAVE_CHECK_TRUE@am__EXEEXT_1 = tests/main$(EXEEXT)
 am__dirstamp = $(am__leading_dot)dirstamp
- at HAVE_CHECK_TRUE@am_tests_check_main_OBJECTS =  \
- at HAVE_CHECK_TRUE@	tests/tests_check_main-check_main.$(OBJEXT) \
- at HAVE_CHECK_TRUE@	tests/tests_check_main-check_core.$(OBJEXT) \
- at HAVE_CHECK_TRUE@	tests/tests_check_main-check_decoder.$(OBJEXT) \
- at HAVE_CHECK_TRUE@	tests/tests_check_main-check_inst.$(OBJEXT) \
- at HAVE_CHECK_TRUE@	tests/tests_check_main-check_session.$(OBJEXT)
-tests_check_main_OBJECTS = $(am_tests_check_main_OBJECTS)
- at HAVE_CHECK_TRUE@tests_check_main_DEPENDENCIES =  \
- at HAVE_CHECK_TRUE@	$(top_builddir)/libsigrokdecode.la
-tests_check_main_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(tests_check_main_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \
-	-o $@
-am__tests_runtc_SOURCES_DIST = tests/runtc.c
- at BUILD_RUNTC_TRUE@am_tests_runtc_OBJECTS =  \
- at BUILD_RUNTC_TRUE@	tests/tests_runtc-runtc.$(OBJEXT)
-tests_runtc_OBJECTS = $(am_tests_runtc_OBJECTS)
-tests_runtc_LDADD = $(LDADD)
-tests_runtc_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(tests_runtc_LDFLAGS) $(LDFLAGS) -o $@
+am_tests_main_OBJECTS = tests/tests_main-main.$(OBJEXT) \
+	tests/tests_main-core.$(OBJEXT) \
+	tests/tests_main-decoder.$(OBJEXT) \
+	tests/tests_main-inst.$(OBJEXT) \
+	tests/tests_main-session.$(OBJEXT)
+tests_main_OBJECTS = $(am_tests_main_OBJECTS)
+tests_main_DEPENDENCIES = libsigrokdecode.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
 AM_V_P = $(am__v_P_ at AM_V@)
 am__v_P_ = $(am__v_P_ at AM_DEFAULT_V@)
 am__v_P_0 = false
@@ -225,20 +198,18 @@ AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
 am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
 am__v_CCLD_0 = @echo "  CCLD    " $@;
 am__v_CCLD_1 = 
-SOURCES = $(libsigrokdecode_la_SOURCES) $(tests_check_main_SOURCES) \
-	$(tests_runtc_SOURCES)
-DIST_SOURCES = $(libsigrokdecode_la_SOURCES) \
-	$(am__tests_check_main_SOURCES_DIST) \
-	$(am__tests_runtc_SOURCES_DIST)
+SOURCES = $(libsigrokdecode_la_SOURCES) $(tests_main_SOURCES)
+DIST_SOURCES = $(libsigrokdecode_la_SOURCES) $(tests_main_SOURCES)
 am__can_run_installinfo = \
   case $$AM_UPDATE_INFO_DIR in \
     n|no|NO) false;; \
     *) (install-info --version) >/dev/null 2>&1;; \
   esac
 DATA = $(pkgconfig_DATA)
-HEADERS = $(library_include_HEADERS) $(noinst_HEADERS)
+HEADERS = $(nodist_pkginclude_HEADERS) $(noinst_HEADERS) \
+	$(pkginclude_HEADERS)
 am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \
-	$(LISP)config.h.in
+	$(LISP)config.h.in version.h.in
 # Read a list of newline-separated strings from the standard input,
 # and print each of them once, without duplicates.  Input order is
 # *not* preserved.
@@ -435,6 +406,19 @@ TEST_LOGS = $(am__test_logs2:.test.log=.log)
 TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/autostuff/test-driver
 TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
 	$(TEST_LOG_FLAGS)
+am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in \
+	$(srcdir)/libsigrokdecode.pc.in $(srcdir)/version.h.in \
+	$(top_srcdir)/autostuff/ar-lib $(top_srcdir)/autostuff/compile \
+	$(top_srcdir)/autostuff/config.guess \
+	$(top_srcdir)/autostuff/config.sub \
+	$(top_srcdir)/autostuff/depcomp \
+	$(top_srcdir)/autostuff/install-sh \
+	$(top_srcdir)/autostuff/ltmain.sh \
+	$(top_srcdir)/autostuff/missing \
+	$(top_srcdir)/autostuff/test-driver AUTHORS COPYING ChangeLog \
+	INSTALL NEWS README autostuff/ar-lib autostuff/compile \
+	autostuff/config.guess autostuff/config.sub autostuff/depcomp \
+	autostuff/install-sh autostuff/ltmain.sh autostuff/missing
 DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 distdir = $(PACKAGE)-$(VERSION)
 top_distdir = $(distdir)
@@ -455,7 +439,6 @@ distcleancheck_listfiles = find . -type f -print
 ACLOCAL = @ACLOCAL@
 AMTAR = @AMTAR@
 AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AM_LIBTOOLFLAGS = @AM_LIBTOOLFLAGS@
 AR = @AR@
 AUTOCONF = @AUTOCONF@
 AUTOHEADER = @AUTOHEADER@
@@ -464,11 +447,10 @@ AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@
 CFLAGS = @CFLAGS@
+CONFIG_STATUS_DEPENDENCIES = @CONFIG_STATUS_DEPENDENCIES@
 CPP = @CPP@
 CPPFLAGS = @CPPFLAGS@
-CPPFLAGS_PYTHON = @CPPFLAGS_PYTHON@
 CYGPATH_W = @CYGPATH_W@
-DECODERS_DIR = @DECODERS_DIR@
 DEFS = @DEFS@
 DEPDIR = @DEPDIR@
 DLLTOOL = @DLLTOOL@
@@ -480,12 +462,6 @@ ECHO_T = @ECHO_T@
 EGREP = @EGREP@
 EXEEXT = @EXEEXT@
 FGREP = @FGREP@
-GLIB_CFLAGS = @GLIB_CFLAGS@
-GLIB_COMPILE_RESOURCES = @GLIB_COMPILE_RESOURCES@
-GLIB_GENMARSHAL = @GLIB_GENMARSHAL@
-GLIB_LIBS = @GLIB_LIBS@
-GLIB_MKENUMS = @GLIB_MKENUMS@
-GOBJECT_QUERY = @GOBJECT_QUERY@
 GREP = @GREP@
 INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
@@ -494,16 +470,15 @@ INSTALL_SCRIPT = @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
 LD = @LD@
 LDFLAGS = @LDFLAGS@
-LDFLAGS_PYTHON = @LDFLAGS_PYTHON@
 LIBOBJS = @LIBOBJS@
 LIBS = @LIBS@
-LIBSIGROK_CFLAGS = @LIBSIGROK_CFLAGS@
-LIBSIGROK_LIBS = @LIBSIGROK_LIBS@
+LIBSIGROKDECODE_CFLAGS = @LIBSIGROKDECODE_CFLAGS@
+LIBSIGROKDECODE_LIBS = @LIBSIGROKDECODE_LIBS@
 LIBTOOL = @LIBTOOL@
 LIPO = @LIPO@
 LN_S = @LN_S@
 LTLIBOBJS = @LTLIBOBJS@
-MAKEFLAGS = @MAKEFLAGS@
+LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
 MAKEINFO = @MAKEINFO@
 MANIFEST_TOOL = @MANIFEST_TOOL@
 MKDIR_P = @MKDIR_P@
@@ -529,16 +504,15 @@ RANLIB = @RANLIB@
 SED = @SED@
 SET_MAKE = @SET_MAKE@
 SHELL = @SHELL@
-SRD_LIB_LDFLAGS = @SRD_LIB_LDFLAGS@
+SRD_EXTRA_CFLAGS = @SRD_EXTRA_CFLAGS@
+SRD_EXTRA_LIBS = @SRD_EXTRA_LIBS@
 SRD_LIB_VERSION = @SRD_LIB_VERSION@
-SRD_LIB_VERSION_AGE = @SRD_LIB_VERSION_AGE@
-SRD_LIB_VERSION_CURRENT = @SRD_LIB_VERSION_CURRENT@
-SRD_LIB_VERSION_REVISION = @SRD_LIB_VERSION_REVISION@
 SRD_PACKAGE_VERSION = @SRD_PACKAGE_VERSION@
-SRD_PACKAGE_VERSION_MAJOR = @SRD_PACKAGE_VERSION_MAJOR@
-SRD_PACKAGE_VERSION_MICRO = @SRD_PACKAGE_VERSION_MICRO@
-SRD_PACKAGE_VERSION_MINOR = @SRD_PACKAGE_VERSION_MINOR@
+SRD_PKGLIBS = @SRD_PKGLIBS@
+SRD_WFLAGS = @SRD_WFLAGS@
 STRIP = @STRIP@
+TESTS_CFLAGS = @TESTS_CFLAGS@
+TESTS_LIBS = @TESTS_LIBS@
 VERSION = @VERSION@
 abs_builddir = @abs_builddir@
 abs_srcdir = @abs_srcdir@
@@ -559,8 +533,6 @@ build_cpu = @build_cpu@
 build_os = @build_os@
 build_vendor = @build_vendor@
 builddir = @builddir@
-check_CFLAGS = @check_CFLAGS@
-check_LIBS = @check_LIBS@
 datadir = @datadir@
 datarootdir = @datarootdir@
 docdir = @docdir@
@@ -577,8 +549,6 @@ infodir = @infodir@
 install_sh = @install_sh@
 libdir = @libdir@
 libexecdir = @libexecdir@
-libsigrok_CFLAGS = @libsigrok_CFLAGS@
-libsigrok_LIBS = @libsigrok_LIBS@
 localedir = @localedir@
 localstatedir = @localstatedir@
 mandir = @mandir@
@@ -588,14 +558,7 @@ pdfdir = @pdfdir@
 prefix = @prefix@
 program_transform_name = @program_transform_name@
 psdir = @psdir@
-python32_CFLAGS = @python32_CFLAGS@
-python32_LIBS = @python32_LIBS@
-python33_CFLAGS = @python33_CFLAGS@
-python33_LIBS = @python33_LIBS@
-python34_CFLAGS = @python34_CFLAGS@
-python34_LIBS = @python34_LIBS@
-python3_CFLAGS = @python3_CFLAGS@
-python3_LIBS = @python3_LIBS@
+runstatedir = @runstatedir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
 srcdir = @srcdir@
@@ -604,7 +567,16 @@ target_alias = @target_alias@
 top_build_prefix = @top_build_prefix@
 top_builddir = @top_builddir@
 top_srcdir = @top_srcdir@
-ACLOCAL_AMFLAGS = -I autostuff
+ACLOCAL_AMFLAGS = -I m4
+AM_LIBTOOLFLAGS = --silent
+GNUMAKEFLAGS = --no-print-directory
+DECODERS_DIR = $(pkgdatadir)/decoders
+ at WIN32_FALSE@AM_CPPFLAGS = -DDECODERS_DIR='"$(DECODERS_DIR)"'
+# Do not hard-code the decoders location on Windows.
+ at WIN32_TRUE@AM_CPPFLAGS = 
+
+# The tests CFLAGS are a superset of the libsigrokdecode CFLAGS.
+AM_CFLAGS = $(SRD_EXTRA_CFLAGS) $(SRD_WFLAGS) $(TESTS_CFLAGS)
 lib_LTLIBRARIES = libsigrokdecode.la
 libsigrokdecode_la_SOURCES = \
 	srd.c \
@@ -620,37 +592,27 @@ libsigrokdecode_la_SOURCES = \
 	error.c \
 	version.c
 
-libsigrokdecode_la_CPPFLAGS = $(CPPFLAGS_PYTHON) \
-	-DDECODERS_DIR='"$(DECODERS_DIR)"'
-
-libsigrokdecode_la_LDFLAGS = $(SRD_LIB_LDFLAGS) $(LDFLAGS_PYTHON)
-library_includedir = $(includedir)/libsigrokdecode
-library_include_HEADERS = libsigrokdecode.h version.h
+libsigrokdecode_la_LIBADD = $(SRD_EXTRA_LIBS) $(LIBSIGROKDECODE_LIBS)
+libsigrokdecode_la_LDFLAGS = -version-info $(SRD_LIB_VERSION) -no-undefined
+pkginclude_HEADERS = libsigrokdecode.h
+nodist_pkginclude_HEADERS = version.h
 noinst_HEADERS = libsigrokdecode-internal.h
 pkgconfigdir = $(libdir)/pkgconfig
 pkgconfig_DATA = libsigrokdecode.pc
 EXTRA_DIST = Doxyfile HACKING contrib/sigrok-logo-notext.png
- at HAVE_CHECK_TRUE@tests_check_main_SOURCES = \
- at HAVE_CHECK_TRUE@	libsigrokdecode.h \
- at HAVE_CHECK_TRUE@	tests/lib.h \
- at HAVE_CHECK_TRUE@	tests/check_main.c \
- at HAVE_CHECK_TRUE@	tests/check_core.c \
- at HAVE_CHECK_TRUE@	tests/check_decoder.c \
- at HAVE_CHECK_TRUE@	tests/check_inst.c \
- at HAVE_CHECK_TRUE@	tests/check_session.c
-
- at HAVE_CHECK_TRUE@tests_check_main_CFLAGS = @check_CFLAGS@
- at HAVE_CHECK_TRUE@tests_check_main_LDADD = $(top_builddir)/libsigrokdecode.la @check_LIBS@
- at HAVE_CHECK_TRUE@tests_check_main_CPPFLAGS = $(CPPFLAGS_PYTHON) \
- at HAVE_CHECK_TRUE@	-DDECODERS_DIR='"$(abs_top_builddir)/decoders"'
-
- at BUILD_RUNTC_TRUE@tests_runtc_SOURCES = tests/runtc.c
- at BUILD_RUNTC_TRUE@tests_runtc_CPPFLAGS = $(CPPFLAGS_PYTHON) $(LIBSIGROK_CFLAGS) \
- at BUILD_RUNTC_TRUE@	-DDECODERS_DIR='"$(abs_top_builddir)/decoders"'
-
- at BUILD_RUNTC_TRUE@tests_runtc_LDFLAGS = -L$(top_builddir) $(LIBSIGROK_LIBS) $(LDFLAGS_PYTHON) -lsigrokdecode
+tests_main_SOURCES = \
+	libsigrokdecode.h \
+	tests/lib.h \
+	tests/main.c \
+	tests/core.c \
+	tests/decoder.c \
+	tests/inst.c \
+	tests/session.c
+
+tests_main_CPPFLAGS = -DDECODERS_TESTDIR='"$(abs_top_srcdir)/decoders"'
+tests_main_LDADD = libsigrokdecode.la $(SRD_EXTRA_LIBS) $(TESTS_LIBS)
 MAINTAINERCLEANFILES = ChangeLog
-all: config.h
+all: config.h version.h
 	$(MAKE) $(AM_MAKEFLAGS) all-am
 
 .SUFFIXES:
@@ -670,7 +632,6 @@ $(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
 	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \
 	$(am__cd) $(top_srcdir) && \
 	  $(AUTOMAKE) --gnu Makefile
-.PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
 	  *config.status*) \
@@ -702,10 +663,16 @@ $(srcdir)/config.h.in:  $(am__configure_deps)
 	rm -f stamp-h1
 	touch $@
 
+version.h: stamp-h2
+	@test -f $@ || rm -f stamp-h2
+	@test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h2
+
+stamp-h2: $(srcdir)/version.h.in $(top_builddir)/config.status
+	@rm -f stamp-h2
+	cd $(top_builddir) && $(SHELL) ./config.status version.h
+
 distclean-hdr:
-	-rm -f config.h stamp-h1
-version.h: $(top_builddir)/config.status $(srcdir)/version.h.in
-	cd $(top_builddir) && $(SHELL) ./config.status $@
+	-rm -f config.h stamp-h1 version.h stamp-h2
 libsigrokdecode.pc: $(top_builddir)/config.status $(srcdir)/libsigrokdecode.pc.in
 	cd $(top_builddir) && $(SHELL) ./config.status $@
 
@@ -755,41 +722,26 @@ clean-checkPROGRAMS:
 	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
 	echo " rm -f" $$list; \
 	rm -f $$list
-
-clean-noinstPROGRAMS:
-	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
 tests/$(am__dirstamp):
 	@$(MKDIR_P) tests
 	@: > tests/$(am__dirstamp)
 tests/$(DEPDIR)/$(am__dirstamp):
 	@$(MKDIR_P) tests/$(DEPDIR)
 	@: > tests/$(DEPDIR)/$(am__dirstamp)
-tests/tests_check_main-check_main.$(OBJEXT): tests/$(am__dirstamp) \
-	tests/$(DEPDIR)/$(am__dirstamp)
-tests/tests_check_main-check_core.$(OBJEXT): tests/$(am__dirstamp) \
+tests/tests_main-main.$(OBJEXT): tests/$(am__dirstamp) \
 	tests/$(DEPDIR)/$(am__dirstamp)
-tests/tests_check_main-check_decoder.$(OBJEXT): tests/$(am__dirstamp) \
+tests/tests_main-core.$(OBJEXT): tests/$(am__dirstamp) \
 	tests/$(DEPDIR)/$(am__dirstamp)
-tests/tests_check_main-check_inst.$(OBJEXT): tests/$(am__dirstamp) \
+tests/tests_main-decoder.$(OBJEXT): tests/$(am__dirstamp) \
 	tests/$(DEPDIR)/$(am__dirstamp)
-tests/tests_check_main-check_session.$(OBJEXT): tests/$(am__dirstamp) \
+tests/tests_main-inst.$(OBJEXT): tests/$(am__dirstamp) \
 	tests/$(DEPDIR)/$(am__dirstamp)
-
-tests/check_main$(EXEEXT): $(tests_check_main_OBJECTS) $(tests_check_main_DEPENDENCIES) $(EXTRA_tests_check_main_DEPENDENCIES) tests/$(am__dirstamp)
-	@rm -f tests/check_main$(EXEEXT)
-	$(AM_V_CCLD)$(tests_check_main_LINK) $(tests_check_main_OBJECTS) $(tests_check_main_LDADD) $(LIBS)
-tests/tests_runtc-runtc.$(OBJEXT): tests/$(am__dirstamp) \
+tests/tests_main-session.$(OBJEXT): tests/$(am__dirstamp) \
 	tests/$(DEPDIR)/$(am__dirstamp)
 
-tests/runtc$(EXEEXT): $(tests_runtc_OBJECTS) $(tests_runtc_DEPENDENCIES) $(EXTRA_tests_runtc_DEPENDENCIES) tests/$(am__dirstamp)
-	@rm -f tests/runtc$(EXEEXT)
-	$(AM_V_CCLD)$(tests_runtc_LINK) $(tests_runtc_OBJECTS) $(tests_runtc_LDADD) $(LIBS)
+tests/main$(EXEEXT): $(tests_main_OBJECTS) $(tests_main_DEPENDENCIES) $(EXTRA_tests_main_DEPENDENCIES) tests/$(am__dirstamp)
+	@rm -f tests/main$(EXEEXT)
+	$(AM_V_CCLD)$(LINK) $(tests_main_OBJECTS) $(tests_main_LDADD) $(LIBS)
 
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -798,24 +750,23 @@ mostlyclean-compile:
 distclean-compile:
 	-rm -f *.tab.c
 
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-decoder.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-error.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-exception.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-instance.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-log.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-module_sigrokdecode.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-session.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-srd.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-type_decoder.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-type_logic.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-util.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libsigrokdecode_la-version.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_check_main-check_core.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_check_main-check_decoder.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_check_main-check_inst.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_check_main-check_main.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_check_main-check_session.Po at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_runtc-runtc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/decoder.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/error.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/exception.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/instance.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/log.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/module_sigrokdecode.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/session.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/srd.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/type_decoder.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/type_logic.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/util.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/version.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_main-core.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_main-decoder.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_main-inst.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_main-main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at tests/$(DEPDIR)/tests_main-session.Po at am__quote@
 
 .c.o:
 @am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
@@ -841,173 +792,75 @@ distclean-compile:
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LTCOMPILE) -c -o $@ $<
 
-libsigrokdecode_la-srd.lo: srd.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-srd.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-srd.Tpo -c -o libsigrokdecode_la-srd.lo `test -f 'srd.c' || echo '$(srcdir)/'`srd.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-srd.Tpo $(DEPDIR)/libsigrokdecode_la-srd.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='srd.c' object='libsigrokdecode_la-srd.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-srd.lo `test -f 'srd.c' || echo '$(srcdir)/'`srd.c
-
-libsigrokdecode_la-session.lo: session.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-session.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-session.Tpo -c -o libsigrokdecode_la-session.lo `test -f 'session.c' || echo '$(srcdir)/'`session.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-session.Tpo $(DEPDIR)/libsigrokdecode_la-session.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='session.c' object='libsigrokdecode_la-session.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-session.lo `test -f 'session.c' || echo '$(srcdir)/'`session.c
-
-libsigrokdecode_la-decoder.lo: decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-decoder.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-decoder.Tpo -c -o libsigrokdecode_la-decoder.lo `test -f 'decoder.c' || echo '$(srcdir)/'`decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-decoder.Tpo $(DEPDIR)/libsigrokdecode_la-decoder.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='decoder.c' object='libsigrokdecode_la-decoder.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-decoder.lo `test -f 'decoder.c' || echo '$(srcdir)/'`decoder.c
-
-libsigrokdecode_la-instance.lo: instance.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-instance.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-instance.Tpo -c -o libsigrokdecode_la-instance.lo `test -f 'instance.c' || echo '$(srcdir)/'`instance.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-instance.Tpo $(DEPDIR)/libsigrokdecode_la-instance.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='instance.c' object='libsigrokdecode_la-instance.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-instance.lo `test -f 'instance.c' || echo '$(srcdir)/'`instance.c
-
-libsigrokdecode_la-log.lo: log.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-log.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-log.Tpo -c -o libsigrokdecode_la-log.lo `test -f 'log.c' || echo '$(srcdir)/'`log.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-log.Tpo $(DEPDIR)/libsigrokdecode_la-log.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='log.c' object='libsigrokdecode_la-log.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-log.lo `test -f 'log.c' || echo '$(srcdir)/'`log.c
-
-libsigrokdecode_la-util.lo: util.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-util.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-util.Tpo -c -o libsigrokdecode_la-util.lo `test -f 'util.c' || echo '$(srcdir)/'`util.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-util.Tpo $(DEPDIR)/libsigrokdecode_la-util.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='util.c' object='libsigrokdecode_la-util.lo' libtool=yes @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-util.lo `test -f 'util.c' || echo '$(srcdir)/'`util.c
-
-libsigrokdecode_la-exception.lo: exception.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-exception.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-exception.Tpo -c -o libsigrokdecode_la-exception.lo `test -f 'exception.c' || echo '$(srcdir)/'`exception.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-exception.Tpo $(DEPDIR)/libsigrokdecode_la-exception.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='exception.c' object='libsigrokdecode_la-exception.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-main.o: tests/main.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-main.o -MD -MP -MF tests/$(DEPDIR)/tests_main-main.Tpo -c -o tests/tests_main-main.o `test -f 'tests/main.c' || echo '$(srcdir)/'`tests/main.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-main.Tpo tests/$(DEPDIR)/tests_main-main.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/main.c' object='tests/tests_main-main.o' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-exception.lo `test -f 'exception.c' || echo '$(srcdir)/'`exception.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-main.o `test -f 'tests/main.c' || echo '$(srcdir)/'`tests/main.c
 
-libsigrokdecode_la-module_sigrokdecode.lo: module_sigrokdecode.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-module_sigrokdecode.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-module_sigrokdecode.Tpo -c -o libsigrokdecode_la-module_sigrokdecode.lo `test -f 'module_sigrokdecode.c' || echo '$(srcdir)/'`module_sigrokdecode.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-module_sigrokdecode.Tpo $(DEPDIR)/libsigrokdecode_la-module_sigrokdecode.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='module_sigrokdecode.c' object='libsigrokdecode_la-module_sigrokdecode.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-main.obj: tests/main.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-main.obj -MD -MP -MF tests/$(DEPDIR)/tests_main-main.Tpo -c -o tests/tests_main-main.obj `if test -f 'tests/main.c'; then $(CYGPATH_W) 'tests/main.c'; else $(CYGPATH_W) '$(srcdir)/tests/main.c'; fi`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-main.Tpo tests/$(DEPDIR)/tests_main-main.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/main.c' object='tests/tests_main-main.obj' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-module_sigrokdecode.lo `test -f 'module_sigrokdecode.c' || echo '$(srcdir)/'`module_sigrokdecode.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-main.obj `if test -f 'tests/main.c'; then $(CYGPATH_W) 'tests/main.c'; else $(CYGPATH_W) '$(srcdir)/tests/main.c'; fi`
 
-libsigrokdecode_la-type_decoder.lo: type_decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-type_decoder.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-type_decoder.Tpo -c -o libsigrokdecode_la-type_decoder.lo `test -f 'type_decoder.c' || echo '$(srcdir)/'`type_decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-type_decoder.Tpo $(DEPDIR)/libsigrokdecode_la-type_decoder.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='type_decoder.c' object='libsigrokdecode_la-type_decoder.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-core.o: tests/core.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-core.o -MD -MP -MF tests/$(DEPDIR)/tests_main-core.Tpo -c -o tests/tests_main-core.o `test -f 'tests/core.c' || echo '$(srcdir)/'`tests/core.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-core.Tpo tests/$(DEPDIR)/tests_main-core.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/core.c' object='tests/tests_main-core.o' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-type_decoder.lo `test -f 'type_decoder.c' || echo '$(srcdir)/'`type_decoder.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-core.o `test -f 'tests/core.c' || echo '$(srcdir)/'`tests/core.c
 
-libsigrokdecode_la-type_logic.lo: type_logic.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-type_logic.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-type_logic.Tpo -c -o libsigrokdecode_la-type_logic.lo `test -f 'type_logic.c' || echo '$(srcdir)/'`type_logic.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-type_logic.Tpo $(DEPDIR)/libsigrokdecode_la-type_logic.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='type_logic.c' object='libsigrokdecode_la-type_logic.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-core.obj: tests/core.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-core.obj -MD -MP -MF tests/$(DEPDIR)/tests_main-core.Tpo -c -o tests/tests_main-core.obj `if test -f 'tests/core.c'; then $(CYGPATH_W) 'tests/core.c'; else $(CYGPATH_W) '$(srcdir)/tests/core.c'; fi`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-core.Tpo tests/$(DEPDIR)/tests_main-core.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/core.c' object='tests/tests_main-core.obj' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-type_logic.lo `test -f 'type_logic.c' || echo '$(srcdir)/'`type_logic.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-core.obj `if test -f 'tests/core.c'; then $(CYGPATH_W) 'tests/core.c'; else $(CYGPATH_W) '$(srcdir)/tests/core.c'; fi`
 
-libsigrokdecode_la-error.lo: error.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-error.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-error.Tpo -c -o libsigrokdecode_la-error.lo `test -f 'error.c' || echo '$(srcdir)/'`error.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-error.Tpo $(DEPDIR)/libsigrokdecode_la-error.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='error.c' object='libsigrokdecode_la-error.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-decoder.o: tests/decoder.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-decoder.o -MD -MP -MF tests/$(DEPDIR)/tests_main-decoder.Tpo -c -o tests/tests_main-decoder.o `test -f 'tests/decoder.c' || echo '$(srcdir)/'`tests/decoder.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-decoder.Tpo tests/$(DEPDIR)/tests_main-decoder.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/decoder.c' object='tests/tests_main-decoder.o' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-error.lo `test -f 'error.c' || echo '$(srcdir)/'`error.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-decoder.o `test -f 'tests/decoder.c' || echo '$(srcdir)/'`tests/decoder.c
 
-libsigrokdecode_la-version.lo: version.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libsigrokdecode_la-version.lo -MD -MP -MF $(DEPDIR)/libsigrokdecode_la-version.Tpo -c -o libsigrokdecode_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libsigrokdecode_la-version.Tpo $(DEPDIR)/libsigrokdecode_la-version.Plo
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='version.c' object='libsigrokdecode_la-version.lo' libtool=yes @AMDEPBACKSLASH@
+tests/tests_main-decoder.obj: tests/decoder.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-decoder.obj -MD -MP -MF tests/$(DEPDIR)/tests_main-decoder.Tpo -c -o tests/tests_main-decoder.obj `if test -f 'tests/decoder.c'; then $(CYGPATH_W) 'tests/decoder.c'; else $(CYGPATH_W) '$(srcdir)/tests/decoder.c'; fi`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-decoder.Tpo tests/$(DEPDIR)/tests_main-decoder.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/decoder.c' object='tests/tests_main-decoder.obj' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsigrokdecode_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libsigrokdecode_la-version.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-decoder.obj `if test -f 'tests/decoder.c'; then $(CYGPATH_W) 'tests/decoder.c'; else $(CYGPATH_W) '$(srcdir)/tests/decoder.c'; fi`
 
-tests/tests_check_main-check_main.o: tests/check_main.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_main.o -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_main.Tpo -c -o tests/tests_check_main-check_main.o `test -f 'tests/check_main.c' || echo '$(srcdir)/'`tests/check_main.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_main.Tpo tests/$(DEPDIR)/tests_check_main-check_main.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_main.c' object='tests/tests_check_main-check_main.o' libtool=no @AMDEPBACKSLASH@
+tests/tests_main-inst.o: tests/inst.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-inst.o -MD -MP -MF tests/$(DEPDIR)/tests_main-inst.Tpo -c -o tests/tests_main-inst.o `test -f 'tests/inst.c' || echo '$(srcdir)/'`tests/inst.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-inst.Tpo tests/$(DEPDIR)/tests_main-inst.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/inst.c' object='tests/tests_main-inst.o' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_main.o `test -f 'tests/check_main.c' || echo '$(srcdir)/'`tests/check_main.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-inst.o `test -f 'tests/inst.c' || echo '$(srcdir)/'`tests/inst.c
 
-tests/tests_check_main-check_main.obj: tests/check_main.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_main.obj -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_main.Tpo -c -o tests/tests_check_main-check_main.obj `if test -f 'tests/check_main.c'; then $(CYGPATH_W) 'tests/check_main.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_main.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_main.Tpo tests/$(DEPDIR)/tests_check_main-check_main.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_main.c' object='tests/tests_check_main-check_main.obj' libtool=no @AMDEPBACKSLASH@
+tests/tests_main-inst.obj: tests/inst.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-inst.obj -MD -MP -MF tests/$(DEPDIR)/tests_main-inst.Tpo -c -o tests/tests_main-inst.obj `if test -f 'tests/inst.c'; then $(CYGPATH_W) 'tests/inst.c'; else $(CYGPATH_W) '$(srcdir)/tests/inst.c'; fi`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-inst.Tpo tests/$(DEPDIR)/tests_main-inst.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/inst.c' object='tests/tests_main-inst.obj' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_main.obj `if test -f 'tests/check_main.c'; then $(CYGPATH_W) 'tests/check_main.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_main.c'; fi`
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-inst.obj `if test -f 'tests/inst.c'; then $(CYGPATH_W) 'tests/inst.c'; else $(CYGPATH_W) '$(srcdir)/tests/inst.c'; fi`
 
-tests/tests_check_main-check_core.o: tests/check_core.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_core.o -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_core.Tpo -c -o tests/tests_check_main-check_core.o `test -f 'tests/check_core.c' || echo '$(srcdir)/'`tests/check_core.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_core.Tpo tests/$(DEPDIR)/tests_check_main-check_core.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_core.c' object='tests/tests_check_main-check_core.o' libtool=no @AMDEPBACKSLASH@
+tests/tests_main-session.o: tests/session.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-session.o -MD -MP -MF tests/$(DEPDIR)/tests_main-session.Tpo -c -o tests/tests_main-session.o `test -f 'tests/session.c' || echo '$(srcdir)/'`tests/session.c
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-session.Tpo tests/$(DEPDIR)/tests_main-session.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/session.c' object='tests/tests_main-session.o' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_core.o `test -f 'tests/check_core.c' || echo '$(srcdir)/'`tests/check_core.c
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-session.o `test -f 'tests/session.c' || echo '$(srcdir)/'`tests/session.c
 
-tests/tests_check_main-check_core.obj: tests/check_core.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_core.obj -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_core.Tpo -c -o tests/tests_check_main-check_core.obj `if test -f 'tests/check_core.c'; then $(CYGPATH_W) 'tests/check_core.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_core.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_core.Tpo tests/$(DEPDIR)/tests_check_main-check_core.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_core.c' object='tests/tests_check_main-check_core.obj' libtool=no @AMDEPBACKSLASH@
+tests/tests_main-session.obj: tests/session.c
+ at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_main-session.obj -MD -MP -MF tests/$(DEPDIR)/tests_main-session.Tpo -c -o tests/tests_main-session.obj `if test -f 'tests/session.c'; then $(CYGPATH_W) 'tests/session.c'; else $(CYGPATH_W) '$(srcdir)/tests/session.c'; fi`
+ at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_main-session.Tpo tests/$(DEPDIR)/tests_main-session.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/session.c' object='tests/tests_main-session.obj' libtool=no @AMDEPBACKSLASH@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_core.obj `if test -f 'tests/check_core.c'; then $(CYGPATH_W) 'tests/check_core.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_core.c'; fi`
-
-tests/tests_check_main-check_decoder.o: tests/check_decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_decoder.o -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_decoder.Tpo -c -o tests/tests_check_main-check_decoder.o `test -f 'tests/check_decoder.c' || echo '$(srcdir)/'`tests/check_decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_decoder.Tpo tests/$(DEPDIR)/tests_check_main-check_decoder.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_decoder.c' object='tests/tests_check_main-check_decoder.o' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_decoder.o `test -f 'tests/check_decoder.c' || echo '$(srcdir)/'`tests/check_decoder.c
-
-tests/tests_check_main-check_decoder.obj: tests/check_decoder.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_decoder.obj -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_decoder.Tpo -c -o tests/tests_check_main-check_decoder.obj `if test -f 'tests/check_decoder.c'; then $(CYGPATH_W) 'tests/check_decoder.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_decoder.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_decoder.Tpo tests/$(DEPDIR)/tests_check_main-check_decoder.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_decoder.c' object='tests/tests_check_main-check_decoder.obj' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_decoder.obj `if test -f 'tests/check_decoder.c'; then $(CYGPATH_W) 'tests/check_decoder.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_decoder.c'; fi`
-
-tests/tests_check_main-check_inst.o: tests/check_inst.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_inst.o -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_inst.Tpo -c -o tests/tests_check_main-check_inst.o `test -f 'tests/check_inst.c' || echo '$(srcdir)/'`tests/check_inst.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_inst.Tpo tests/$(DEPDIR)/tests_check_main-check_inst.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_inst.c' object='tests/tests_check_main-check_inst.o' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_inst.o `test -f 'tests/check_inst.c' || echo '$(srcdir)/'`tests/check_inst.c
-
-tests/tests_check_main-check_inst.obj: tests/check_inst.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_inst.obj -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_inst.Tpo -c -o tests/tests_check_main-check_inst.obj `if test -f 'tests/check_inst.c'; then $(CYGPATH_W) 'tests/check_inst.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_inst.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_inst.Tpo tests/$(DEPDIR)/tests_check_main-check_inst.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_inst.c' object='tests/tests_check_main-check_inst.obj' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_inst.obj `if test -f 'tests/check_inst.c'; then $(CYGPATH_W) 'tests/check_inst.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_inst.c'; fi`
-
-tests/tests_check_main-check_session.o: tests/check_session.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_session.o -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_session.Tpo -c -o tests/tests_check_main-check_session.o `test -f 'tests/check_session.c' || echo '$(srcdir)/'`tests/check_session.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_session.Tpo tests/$(DEPDIR)/tests_check_main-check_session.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_session.c' object='tests/tests_check_main-check_session.o' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_session.o `test -f 'tests/check_session.c' || echo '$(srcdir)/'`tests/check_session.c
-
-tests/tests_check_main-check_session.obj: tests/check_session.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -MT tests/tests_check_main-check_session.obj -MD -MP -MF tests/$(DEPDIR)/tests_check_main-check_session.Tpo -c -o tests/tests_check_main-check_session.obj `if test -f 'tests/check_session.c'; then $(CYGPATH_W) 'tests/check_session.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_session.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_check_main-check_session.Tpo tests/$(DEPDIR)/tests_check_main-check_session.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/check_session.c' object='tests/tests_check_main-check_session.obj' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_check_main_CPPFLAGS) $(CPPFLAGS) $(tests_check_main_CFLAGS) $(CFLAGS) -c -o tests/tests_check_main-check_session.obj `if test -f 'tests/check_session.c'; then $(CYGPATH_W) 'tests/check_session.c'; else $(CYGPATH_W) '$(srcdir)/tests/check_session.c'; fi`
-
-tests/tests_runtc-runtc.o: tests/runtc.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_runtc_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_runtc-runtc.o -MD -MP -MF tests/$(DEPDIR)/tests_runtc-runtc.Tpo -c -o tests/tests_runtc-runtc.o `test -f 'tests/runtc.c' || echo '$(srcdir)/'`tests/runtc.c
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_runtc-runtc.Tpo tests/$(DEPDIR)/tests_runtc-runtc.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/runtc.c' object='tests/tests_runtc-runtc.o' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_runtc_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_runtc-runtc.o `test -f 'tests/runtc.c' || echo '$(srcdir)/'`tests/runtc.c
-
-tests/tests_runtc-runtc.obj: tests/runtc.c
- at am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_runtc_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT tests/tests_runtc-runtc.obj -MD -MP -MF tests/$(DEPDIR)/tests_runtc-runtc.Tpo -c -o tests/tests_runtc-runtc.obj `if test -f 'tests/runtc.c'; then $(CYGPATH_W) 'tests/runtc.c'; else $(CYGPATH_W) '$(srcdir)/tests/runtc.c'; fi`
- at am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) tests/$(DEPDIR)/tests_runtc-runtc.Tpo tests/$(DEPDIR)/tests_runtc-runtc.Po
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tests/runtc.c' object='tests/tests_runtc-runtc.obj' libtool=no @AMDEPBACKSLASH@
- at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
- at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_runtc_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_runtc-runtc.obj `if test -f 'tests/runtc.c'; then $(CYGPATH_W) 'tests/runtc.c'; else $(CYGPATH_W) '$(srcdir)/tests/runtc.c'; fi`
+ at am__fastdepCC_FALSE@	$(AM_V_CC at am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(tests_main_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o tests/tests_main-session.obj `if test -f 'tests/session.c'; then $(CYGPATH_W) 'tests/session.c'; else $(CYGPATH_W) '$(srcdir)/tests/session.c'; fi`
 
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -1039,27 +892,48 @@ uninstall-pkgconfigDATA:
 	@list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \
 	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
 	dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir)
-install-library_includeHEADERS: $(library_include_HEADERS)
+install-nodist_pkgincludeHEADERS: $(nodist_pkginclude_HEADERS)
+	@$(NORMAL_INSTALL)
+	@list='$(nodist_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
+	if test -n "$$list"; then \
+	  echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \
+	fi; \
+	for p in $$list; do \
+	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \
+	done
+
+uninstall-nodist_pkgincludeHEADERS:
+	@$(NORMAL_UNINSTALL)
+	@list='$(nodist_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
+	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir)
+install-pkgincludeHEADERS: $(pkginclude_HEADERS)
 	@$(NORMAL_INSTALL)
-	@list='$(library_include_HEADERS)'; test -n "$(library_includedir)" || list=; \
+	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
 	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(library_includedir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(library_includedir)" || exit 1; \
+	  echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \
 	fi; \
 	for p in $$list; do \
 	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
 	  echo "$$d$$p"; \
 	done | $(am__base_list) | \
 	while read files; do \
-	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(library_includedir)'"; \
-	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(library_includedir)" || exit $$?; \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \
 	done
 
-uninstall-library_includeHEADERS:
+uninstall-pkgincludeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list='$(library_include_HEADERS)'; test -n "$(library_includedir)" || list=; \
+	@list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \
 	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-	dir='$(DESTDIR)$(library_includedir)'; $(am__uninstall_files_from_dir)
+	dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir)
 
 ID: $(am__tagged_files)
 	$(am__define_uniq_tagged_files); mkid -fID $$unique
@@ -1150,7 +1024,7 @@ $(TEST_SUITE_LOG): $(TEST_LOGS)
 	if test -n "$$am__remaking_logs"; then \
 	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
 	       "recursion detected" >&2; \
-	else \
+	elif test -n "$$redo_logs"; then \
 	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
 	fi; \
 	if $(am__make_dryrun); then :; else \
@@ -1261,9 +1135,9 @@ recheck: all $(check_PROGRAMS)
 	        am__force_recheck=am--force-recheck \
 	        TEST_LOGS="$$log_list"; \
 	exit $$?
-tests/check_main.log: tests/check_main$(EXEEXT)
-	@p='tests/check_main$(EXEEXT)'; \
-	b='tests/check_main'; \
+tests/main.log: tests/main$(EXEEXT)
+	@p='tests/main$(EXEEXT)'; \
+	b='tests/main'; \
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
@@ -1348,15 +1222,15 @@ dist-xz: distdir
 	$(am__post_remove_distdir)
 
 dist-tarZ: distdir
-	@echo WARNING: "Support for shar distribution archives is" \
-	               "deprecated." >&2
+	@echo WARNING: "Support for distribution archives compressed with" \
+		       "legacy program 'compress' is deprecated." >&2
 	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
 	tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
 	$(am__post_remove_distdir)
 
 dist-shar: distdir
-	@echo WARNING: "Support for distribution archives compressed with" \
-		       "legacy program 'compress' is deprecated." >&2
+	@echo WARNING: "Support for shar distribution archives is" \
+	               "deprecated." >&2
 	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
 	shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
 	$(am__post_remove_distdir)
@@ -1392,17 +1266,17 @@ distcheck: dist
 	esac
 	chmod -R a-w $(distdir)
 	chmod u+w $(distdir)
-	mkdir $(distdir)/_build $(distdir)/_inst
+	mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst
 	chmod a-w $(distdir)
 	test -d $(distdir)/_build || exit 0; \
 	dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
 	  && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
 	  && am__cwd=`pwd` \
-	  && $(am__cd) $(distdir)/_build \
-	  && ../configure \
+	  && $(am__cd) $(distdir)/_build/sub \
+	  && ../../configure \
 	    $(AM_DISTCHECK_CONFIGURE_FLAGS) \
 	    $(DISTCHECK_CONFIGURE_FLAGS) \
-	    --srcdir=.. --prefix="$$dc_install_base" \
+	    --srcdir=../.. --prefix="$$dc_install_base" \
 	  && $(MAKE) $(AM_MAKEFLAGS) \
 	  && $(MAKE) $(AM_MAKEFLAGS) dvi \
 	  && $(MAKE) $(AM_MAKEFLAGS) check \
@@ -1459,10 +1333,9 @@ check-am: all-am
 	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
 	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
 check: check-am
-all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(DATA) $(HEADERS) \
-		config.h
+all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) config.h version.h
 installdirs:
-	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgconfigdir)" "$(DESTDIR)$(library_includedir)"; do \
+	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgconfigdir)" "$(DESTDIR)$(pkgincludedir)" "$(DESTDIR)$(pkgincludedir)"; do \
 	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
 	done
 install: install-am
@@ -1504,7 +1377,7 @@ maintainer-clean-generic:
 clean: clean-am
 
 clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
-	clean-libtool clean-noinstPROGRAMS mostlyclean-am
+	clean-libtool mostlyclean-am
 
 distclean: distclean-am
 	-rm -f $(am__CONFIG_DISTCLEAN_FILES)
@@ -1525,7 +1398,8 @@ info: info-am
 
 info-am:
 
-install-data-am: install-library_includeHEADERS install-pkgconfigDATA
+install-data-am: install-nodist_pkgincludeHEADERS \
+	install-pkgconfigDATA install-pkgincludeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
 install-dvi: install-dvi-am
@@ -1575,36 +1449,40 @@ ps: ps-am
 ps-am:
 
 uninstall-am: uninstall-libLTLIBRARIES \
-	uninstall-library_includeHEADERS uninstall-pkgconfigDATA
+	uninstall-nodist_pkgincludeHEADERS uninstall-pkgconfigDATA \
+	uninstall-pkgincludeHEADERS
 
 .MAKE: all check-am install-am install-data-am install-strip
 
 .PHONY: CTAGS GTAGS TAGS all all-am am--refresh check check-TESTS \
 	check-am clean clean-checkPROGRAMS clean-cscope clean-generic \
-	clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS cscope \
-	cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \
-	dist-gzip dist-hook dist-lzip dist-shar dist-tarZ dist-xz \
-	dist-zip distcheck distclean distclean-compile \
-	distclean-generic distclean-hdr distclean-libtool \
-	distclean-tags distcleancheck distdir distuninstallcheck dvi \
-	dvi-am html html-am info info-am install install-am \
-	install-data install-data-am install-data-hook install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am \
-	install-libLTLIBRARIES install-library_includeHEADERS \
-	install-man install-pdf install-pdf-am install-pkgconfigDATA \
-	install-ps install-ps-am install-strip installcheck \
-	installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	recheck tags tags-am uninstall uninstall-am \
-	uninstall-libLTLIBRARIES uninstall-library_includeHEADERS \
-	uninstall-pkgconfigDATA
-
-
-.PHONY: ChangeLog
+	clean-libLTLIBRARIES clean-libtool cscope cscopelist-am ctags \
+	ctags-am dist dist-all dist-bzip2 dist-gzip dist-hook \
+	dist-lzip dist-shar dist-tarZ dist-xz dist-zip distcheck \
+	distclean distclean-compile distclean-generic distclean-hdr \
+	distclean-libtool distclean-tags distcleancheck distdir \
+	distuninstallcheck dvi dvi-am html html-am info info-am \
+	install install-am install-data install-data-am \
+	install-data-hook install-dvi install-dvi-am install-exec \
+	install-exec-am install-html install-html-am install-info \
+	install-info-am install-libLTLIBRARIES install-man \
+	install-nodist_pkgincludeHEADERS install-pdf install-pdf-am \
+	install-pkgconfigDATA install-pkgincludeHEADERS install-ps \
+	install-ps-am install-strip installcheck installcheck-am \
+	installdirs maintainer-clean maintainer-clean-generic \
+	mostlyclean mostlyclean-compile mostlyclean-generic \
+	mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \
+	uninstall uninstall-am uninstall-libLTLIBRARIES \
+	uninstall-nodist_pkgincludeHEADERS uninstall-pkgconfigDATA \
+	uninstall-pkgincludeHEADERS
+
+.PRECIOUS: Makefile
+
+
+.PHONY: ChangeLog install-decoders
+
 ChangeLog:
-	git --git-dir $(top_srcdir)/.git log > ChangeLog || touch ChangeLog
+	git --git-dir '$(top_srcdir)/.git' log >$@ || touch $@
 
 dist-hook: ChangeLog
 	$(MKDIR_P) $(distdir)/tools
diff --git a/NEWS b/NEWS
index bd21b02..a98c7fb 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,235 @@
+0.4.1 (2016-12-27)
+------------------
+
+Note: This release does NOT change the libsigrokdecode public C API. This
+means existing libsigrokdecode frontends should not require any changes.
+However, individual PDs and their output changed, which may require
+some adaptations on the user's side in some cases.
+
+ * New supported protocol decoders:
+   - aud              Renesas/Hitachi Advanced User Debugger (AUD) protocol
+   - avr_pdi          Atmel proprietary interface for the ATxmega MCU
+   - dmx512           Professional lighting control protocol
+   - em4305           EM4205/EM4305 100-150kHz RFID protocol
+   - gpib             IEEE-488 GPIB / HPIB protocol
+   - ps2              PS/2 keyboard/mouse interface
+   - rgb_led_ws281x   RGB LED string protocol (WS281x)
+   - ssi32            Synchronous Serial Interface (32bit) protocol
+   - t55xx            T55xx 100-150kHz RFID protocol
+   - wiegand          Wiegand interface for electronic entry systems
+ * Introduce a decoders/common facility for code shared between PDs (bug #804).
+ * Supply metadata to all stacked decoders, not just low-level ones (bug #664).
+ * Various Doxygen/documentation improvements.
+ * Factor out a srd_decoder_apiver() internal helper function.
+ * srd_inst_decode(): Return SRD_ERR_ARG if unitsize is 0.
+ * Print error messages when decoders fail load time checks (bug #704).
+ * Fix multiple valgrind warnings (memory leaks and such).
+ * Build system: Sort PD list alphabetically in "make install".
+ * mdio:
+   - Replace PD with a new implementation that also supports Clause 22 and 45.
+   - Improve annotations slightly.
+ * xfp:
+   - Move various constants to common/plugtrx for reusability purposes.
+ * sdcard_{sd,spi}:
+   - Move various constants to common/sdcard for reusability purposes.
+ * usb_request:
+   - Drop hardcoded samplerate (workaround for the fixed bug #664).
+ * spiflash:
+   - Handle CS# transitions, allow variable-length transfers.
+   - Handle "Fast Read Dual I/O" commands.
+   - Add a "format" decoder option.
+   - Implement Release Power-down / Device ID (0xAB) command (bug #845).
+   - Remove hardcoded Macronix references.
+   - Add initial FIDELIX FM25Q32 metadata/support.
+   - Implement WRSR, RDSR2 commands.
+   - Various annotation improvements.
+ * timing:
+   - Add frequency and averaging support.
+ * midi:
+   - Decode note names and percussion names (e.g. 'G2', 'Tambourine').
+   - Decode instrument names and drum_kit names (e.g. 'GS Orchestra Kit').
+   - Handle Polyphonic Pressure / Aftertouch (message 0xAn).
+   - Handle Program Change (message 0xCn).
+   - Handle Channel Pressure / Aftertouch (message 0xDn).
+   - Handle Channel Mode (message 0xBn mm where mm is 120 through 127).
+   - Handle System Common messages (message 0xF1 through 0xF6), including
+     full time code decoding.
+   - SysEx decoding now decodes the 1-3 byte manufacturer field, payload
+     is now displayed as hex.
+   - 'undefined' fields now display the value (e.g. 'undefined 0xf4').
+   - Add 'MSB' and 'LSB' to many control_functions entries.
+   - Fix "trapped in state X" bug with handle_channel_msg_generic(),
+     though this might be dead code.
+   - Fix bug in sysex_manufacturer_ids; 1-byte manufacturers were not
+     tuples due to missing comma.
+   - Fix bug in SysEx state machine; 0xF7 now sent to handle_sysex_msg().
+   - Annotations: Provide multiple string versions (shorter and longer ones).
+   - chromatic_notes in list.py was off by 1 octave.
+   - Handle "Running Status" where status byte can be omitted.
+   - SysEx message can be terminated by status byte, not just EOX.
+   - Handle SysReal messages that interrupt in-progress message transmission.
+   - Identify and print garbage / truncated data.
+   - Add 2 new annotations: text-sysreal-verbose and text-error.
+ * usb_power_delivery:
+   - Drop problematic exception in us2samples() function (bug #758).
+ * uart:
+   - Fix a bug in the output for stacked PDs (when there's RX/TX overlap).
+   - Various output formatting improvements (e.g. for ASCII and octal).
+   - Skip frames with invalid start bits.
+   - Emit 2 bytes for 9-bit UART binary output (bug #708).
+   - Default to hex format datavalue annotations.
+ * spi:
+   - Fix binary output for wordsizes > 8 (bug #686).
+ * Various decoders:
+   - Fix some incorrect PD license metadata fields.
+   - Fix typos, whitespace issues and random other cosmetics in some PDs.
+   - Use consistent __init__() format across all PDs.
+   - Move some duplicated code snippets/lists to decoders/common.
+
+0.4.0 (2016-01-29)
+------------------
+
+Note: This release DOES change the libsigrokdecode public C API. This
+means it is NOT backwards-compatible and frontends will need updates.
+
+ * New supported protocol decoders:
+   - adns5020       Bidirectional command and data over an SPI-like protocol
+   - am230x         Aosong AM230x/DHTxx/RHTxx humidity/temperature sensor
+   - arm_etmv3      Decode ETM instruction trace packets
+   - arm_itm        Trace data from Cortex-M / ARMv7m ITM module
+   - arm_tpiu       Filter TPIU formatted trace data into separate streams
+   - eeprom24xx     24xx series I²C EEPROM protocol
+   - em4100         EM4100 100-150kHz RFID protocol
+   - jitter         Retrieves the timing jitter between two digital signals
+   - max7219        8-digit LED display driver
+   - mdio           Half-duplex sync serial bus for MII management (MAC/PHY)
+   - modbus         Modbus RTU protocol for industrial applications
+   - mrf24j40       IEEE 802.15.4 2.4 GHz RF tranceiver chip
+   - nrf24l01       2.4GHz transceiver chip
+   - pwm            Analog level encoded in duty cycle percentage
+   - qi             Async serial protocol for Qi charger receivers
+   - rfm12          HopeRF RFM12 wireless transceiver control protocol
+   - sdcard_sd      Secure Digital card (SD mode) low-level protocol
+   - spdif          Serial bus for connecting digital audio devices
+   - stepper_motor  Absolute position and movement speed from step/dir
+   - swd            Two-wire protocol for debug access to ARM CPUs
+   - tca6408a       Texas Instruments TCA6408A 8-bit I²C I/O expander
+   - timing         Calculate time between edges
+   - usb_power_delivery USB Power Delivery protocol
+   - usb_request    USB (low-speed and full-speed) transaction/request protocol
+ * The 'mx25lxx05d' decoder was renamed to 'spiflash' and made more generic.
+ * arm_itm:
+   - Use objdump instead of addr2line (bug #564).
+ * can:
+   - Emit bit value annotations.
+   - Improve stuff bit annotation placement.
+ * ds1307:
+   - Emit per-bit annotations for registers.
+   - Add more annotation classes (and annotation rows).
+   - Handle register 0x07 (control register).
+   - Handle SRAM register accesses.
+   - Correctly handle address wrap-around.
+   - Warn about (and ignore) non-DS1307 traffic.
+ * edid:
+   - Handle more EDID structure sections.
+   - Add annotation rows.
+ * jitter:
+   - Avoid Unicode string literals (bug #569).
+ * jtag:
+   - Fix/enable OUT_PYTHON output.
+   - Add more annotations, fix a SHIFT-IR/-DR issue.
+ * jtag_stm32:
+   - Fix incorrect handling of registers.
+   - Decode more fields, improve IDCODE handling.
+   - Decode IDCODE contents as strings (not just hex values).
+ * midi:
+   - Fix two incorrect sample numbers.
+   - Update for a change (emit databyte/bits at the same time) in the uart PD.
+ * mrf24j40:
+   - Fix a register address typo.
+ * nunchuk:
+   - Fix inverted button press logic.
+ * pan1321:
+   - Update for a change (emit databyte/bits at the same time) in the uart PD.
+ * onewire_link:
+   - Fix a bug when the samplerate is too low for the PD (bug #357).
+ * parallel:
+   - Enforce that at least one pin must be provided.
+ * pwm:
+   - Avoid Unicode string literals (bug #569).
+ * spi:
+   - OUT_PYTHON docs: Fix order of MISO/MOSI data items.
+   - Tell stacked decoders about missing CS# signal.
+   - Add binary output facilities for MISO/MOSI (bug #424).
+   - Don't decode data lines if CS# isn't asserted (bug #559).
+   - Add a 'TRANSFER' output type.
+ * spiflash:
+   - Implement FAST READ command.
+   - Add a 'chip' option in preparation for supporting more devices.
+   - Fix incorrect 'inputs' field.
+ * tlc5620:
+   - Fix incorrect DAC selection decode, add more annotations.
+   - Only decode the last 11 bits, ignore the rest.
+   - Properly handle LOAD and LDAC based operations.
+   - Handle the case of less than 11 bits in a command.
+   - Add options for per-DAC Vref, show voltages.
+ * uart:
+   - Add signal inversion options 'invert_tx' and 'invert_rx'.
+   - Emit databyte and bits list at the same time to simplify stacked PDs.
+   - Improve sample positions at high data rates.
+   - Handle framing errors better.
+   - Performance-optimize handling of samples when TX and RX are both idle.
+ * usb_packet:
+   - Fix incorrect DATA*/MDATA handling (bug #623).
+   - Handle invalid packets more gracefully (bug #186).
+   - Calculate and check CRC5/CRC16.
+   - Handle errors from usb_signalling.
+   - Handle PREamble transmissions.
+ * usb_request:
+   - Handle transmission timeouts.
+   - Handle PREamble transmissions.
+ * usb_signalling:
+   - Track USB symbol width to compensate frequency errors.
+   - Detect bit stuffing errors.
+   - Handle symbol errors in EOP state.
+   - Use explicit positions for packet start/end (avoids glitches).
+   - Decode RESET and Keep-Alive signalling conditions.
+   - Add option to automatically set signalling speed.
+   - Fix SOP detection after an error condition.
+   - Add signalling states needed after LS PREamble PID.
+   - Detect PREamble PID.
+ * Drop the PD testing framework. It's in the 'sigrok-test' repository now
+   (and is not meant for "end users" or distro packages anyway; it's a pure
+   developer tool/system). This also fixes some PD test related build issues.
+ * Makefile.am: Use libtool's -no-undefined option (fixes MinGW shared build).
+ * Support loading decoders stored in ZIP files.
+ * Updated build requirements:
+   - libglib >= 2.28.0
+   - Drop obsolete (optional) dependencies: python3-coverage, libsigrok.
+ * README: Use clearer descriptions for the dependencies.
+ * Remove all references to the obsolete sigrok-commits mailing list.
+ * Fix incorrect doxygen comment for srd_decoder_list() function (bug #378).
+ * configure.ac:
+   - Fix a shell portability issue ("==" vs. "=").
+   - Use AM_CFLAGS instead of CFLAGS.
+   - Only link the 'check' library into the unit tests (not the lib).
+ * Unit tests:
+   - Fix out-of-tree build.
+ * libsigrokdecode.pc (pkg-config) file:
+   - Fix an issue related to the Python lib dependencies.
+   - Publish decodersdir variable.
+ * Add "-git-<hash>" suffix to development version numbers.
+ * Pass unitsize per sample chunk (bug #352).
+ * Modernize the whole autotools setup.
+ * Build with _POSIX_C_SOURCE=200112L per default.
+ * Build: Show CC and CFLAGS in configuration summary.
+ * Also look for decoders in XDG data directories.
+ * Restrict Python code to stable ABI subset (PEP 384).
+ * Fix various memory leaks.
+ * Fix an issue with PDs not being properly removed upon unload.
+ * Don't let Python override signal handlers (bug #461).
+ * configure: Also check for Python 3.5 (bug #739).
+
 0.3.0 (2014-05-06)
 ------------------
 
@@ -64,10 +296,10 @@ means it is NOT backwards-compatible and frontends will need updates.
    - Either MISO or MOSI can be optional now, but not both (bug #175).
    - The CS# pin is optional now. If the pin is supplied, it is honored
      (decoding only happens when the pin is asserted). Otherwise decoding will
-     use every CLK edge, regardless of CS# state or CS# existance (bug #152).
+     use every CLK edge, regardless of CS# state or CS# existence (bug #152).
    - Rename the 'SCK' pin to the more common 'CLK'.
    - Output bit-exact annotations and data for use by stacked PDs.
-   - Fix a bug occuring when only MOSI (but not MISO) was supplied.
+   - Fix a bug occurring when only MOSI (but not MISO) was supplied.
  * transitioncounter:
    - Drop the obsolete 'transitioncounter' dummy protocol decoder.
  * uart:
diff --git a/README b/README
index fa30ef0..686efef 100644
--- a/README
+++ b/README
@@ -27,18 +27,18 @@ Distro packagers should only use released tarballs (no git snapshots).
 Requirements
 ------------
 
- - git
- - gcc (>= 4.0)
+ - git (only needed when building from git)
+ - gcc (>= 4.0) or clang
  - make
- - autoconf >= 2.63
- - automake >= 1.11
- - libtool
+ - autoconf >= 2.63 (only needed when building from git)
+ - automake >= 1.11 (only needed when building from git)
+ - libtool (only needed when building from git)
  - pkg-config >= 0.22
- - libglib >= 2.24.0
+ - libglib >= 2.28.0
  - Python >= 3.2
  - check >= 0.9.4 (optional, only needed to run unit tests)
- - libsigrok >= 0.3.0 (optional, only needed for the developer PD tests)
- - python3-coverage (optional, only needed for the developer PD tests)
+ - doxygen (optional, only needed for the C API docs)
+ - graphviz (optional, only needed for the C API docs)
 
 
 Building and installing
@@ -82,13 +82,10 @@ the library as a whole is licensed under the terms of the GPLv3+.
 Please see the individual source files for the full list of copyright holders.
 
 
-Mailing lists
--------------
-
-There are two mailing lists for sigrok/libsigrokdecode:
+Mailing list
+------------
 
  https://lists.sourceforge.net/lists/listinfo/sigrok-devel
- https://lists.sourceforge.net/lists/listinfo/sigrok-commits
 
 
 IRC
diff --git a/aclocal.m4 b/aclocal.m4
index 9a85aac..671f2bc 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -1,6 +1,6 @@
-# generated automatically by aclocal 1.14.1 -*- Autoconf -*-
+# generated automatically by aclocal 1.15 -*- Autoconf -*-
 
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+# Copyright (C) 1996-2014 Free Software Foundation, Inc.
 
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -20,244 +20,63 @@ You have another version of autoconf.  It may work, but is not guaranteed to.
 If you have problems, you may need to regenerate the build system entirely.
 To do so, use the procedure documented by the package, typically 'autoreconf'.])])
 
-# Configure paths for GLIB
-# Owen Taylor     1997-2001
-
-dnl AM_PATH_GLIB_2_0([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND [, MODULES]]]])
-dnl Test for GLIB, and define GLIB_CFLAGS and GLIB_LIBS, if gmodule, gobject,
-dnl gthread, or gio is specified in MODULES, pass to pkg-config
+dnl pkg.m4 - Macros to locate and utilise pkg-config.   -*- Autoconf -*-
+dnl serial 11 (pkg-config-0.29)
 dnl
-AC_DEFUN([AM_PATH_GLIB_2_0],
-[dnl 
-dnl Get the cflags and libraries from pkg-config
+dnl Copyright © 2004 Scott James Remnant <scott at netsplit.com>.
+dnl Copyright © 2012-2015 Dan Nicholson <dbn.lists at gmail.com>
 dnl
-AC_ARG_ENABLE(glibtest, [  --disable-glibtest      do not try to compile and run a test GLIB program],
-		    , enable_glibtest=yes)
-
-  pkg_config_args=glib-2.0
-  for module in . $4
-  do
-      case "$module" in
-         gmodule) 
-             pkg_config_args="$pkg_config_args gmodule-2.0"
-         ;;
-         gmodule-no-export) 
-             pkg_config_args="$pkg_config_args gmodule-no-export-2.0"
-         ;;
-         gobject) 
-             pkg_config_args="$pkg_config_args gobject-2.0"
-         ;;
-         gthread) 
-             pkg_config_args="$pkg_config_args gthread-2.0"
-         ;;
-         gio*) 
-             pkg_config_args="$pkg_config_args $module-2.0"
-         ;;
-      esac
-  done
-
-  PKG_PROG_PKG_CONFIG([0.16])
-
-  no_glib=""
-
-  if test "x$PKG_CONFIG" = x ; then
-    no_glib=yes
-    PKG_CONFIG=no
-  fi
-
-  min_glib_version=ifelse([$1], ,2.0.0,$1)
-  AC_MSG_CHECKING(for GLIB - version >= $min_glib_version)
-
-  if test x$PKG_CONFIG != xno ; then
-    ## don't try to run the test against uninstalled libtool libs
-    if $PKG_CONFIG --uninstalled $pkg_config_args; then
-	  echo "Will use uninstalled version of GLib found in PKG_CONFIG_PATH"
-	  enable_glibtest=no
-    fi
-
-    if $PKG_CONFIG --atleast-version $min_glib_version $pkg_config_args; then
-	  :
-    else
-	  no_glib=yes
-    fi
-  fi
-
-  if test x"$no_glib" = x ; then
-    GLIB_GENMARSHAL=`$PKG_CONFIG --variable=glib_genmarshal glib-2.0`
-    GOBJECT_QUERY=`$PKG_CONFIG --variable=gobject_query glib-2.0`
-    GLIB_MKENUMS=`$PKG_CONFIG --variable=glib_mkenums glib-2.0`
-    GLIB_COMPILE_RESOURCES=`$PKG_CONFIG --variable=glib_compile_resources gio-2.0`
-
-    GLIB_CFLAGS=`$PKG_CONFIG --cflags $pkg_config_args`
-    GLIB_LIBS=`$PKG_CONFIG --libs $pkg_config_args`
-    glib_config_major_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
-    glib_config_minor_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
-    glib_config_micro_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
-    if test "x$enable_glibtest" = "xyes" ; then
-      ac_save_CFLAGS="$CFLAGS"
-      ac_save_LIBS="$LIBS"
-      CFLAGS="$CFLAGS $GLIB_CFLAGS"
-      LIBS="$GLIB_LIBS $LIBS"
+dnl This program is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2 of the License, or
+dnl (at your option) any later version.
 dnl
-dnl Now check if the installed GLIB is sufficiently new. (Also sanity
-dnl checks the results of pkg-config to some extent)
+dnl This program is distributed in the hope that it will be useful, but
+dnl WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+dnl General Public License for more details.
 dnl
-      rm -f conf.glibtest
-      AC_TRY_RUN([
-#include <glib.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-int 
-main ()
-{
-  unsigned int major, minor, micro;
-
-  fclose (fopen ("conf.glibtest", "w"));
-
-  if (sscanf("$min_glib_version", "%u.%u.%u", &major, &minor, &micro) != 3) {
-     printf("%s, bad version string\n", "$min_glib_version");
-     exit(1);
-   }
-
-  if ((glib_major_version != $glib_config_major_version) ||
-      (glib_minor_version != $glib_config_minor_version) ||
-      (glib_micro_version != $glib_config_micro_version))
-    {
-      printf("\n*** 'pkg-config --modversion glib-2.0' returned %d.%d.%d, but GLIB (%d.%d.%d)\n", 
-             $glib_config_major_version, $glib_config_minor_version, $glib_config_micro_version,
-             glib_major_version, glib_minor_version, glib_micro_version);
-      printf ("*** was found! If pkg-config was correct, then it is best\n");
-      printf ("*** to remove the old version of GLib. You may also be able to fix the error\n");
-      printf("*** by modifying your LD_LIBRARY_PATH enviroment variable, or by editing\n");
-      printf("*** /etc/ld.so.conf. Make sure you have run ldconfig if that is\n");
-      printf("*** required on your system.\n");
-      printf("*** If pkg-config was wrong, set the environment variable PKG_CONFIG_PATH\n");
-      printf("*** to point to the correct configuration files\n");
-    } 
-  else if ((glib_major_version != GLIB_MAJOR_VERSION) ||
-	   (glib_minor_version != GLIB_MINOR_VERSION) ||
-           (glib_micro_version != GLIB_MICRO_VERSION))
-    {
-      printf("*** GLIB header files (version %d.%d.%d) do not match\n",
-	     GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
-      printf("*** library (version %d.%d.%d)\n",
-	     glib_major_version, glib_minor_version, glib_micro_version);
-    }
-  else
-    {
-      if ((glib_major_version > major) ||
-        ((glib_major_version == major) && (glib_minor_version > minor)) ||
-        ((glib_major_version == major) && (glib_minor_version == minor) && (glib_micro_version >= micro)))
-      {
-        return 0;
-       }
-     else
-      {
-        printf("\n*** An old version of GLIB (%u.%u.%u) was found.\n",
-               glib_major_version, glib_minor_version, glib_micro_version);
-        printf("*** You need a version of GLIB newer than %u.%u.%u. The latest version of\n",
-	       major, minor, micro);
-        printf("*** GLIB is always available from ftp://ftp.gtk.org.\n");
-        printf("***\n");
-        printf("*** If you have already installed a sufficiently new version, this error\n");
-        printf("*** probably means that the wrong copy of the pkg-config shell script is\n");
-        printf("*** being found. The easiest way to fix this is to remove the old version\n");
-        printf("*** of GLIB, but you can also set the PKG_CONFIG environment to point to the\n");
-        printf("*** correct copy of pkg-config. (In this case, you will have to\n");
-        printf("*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf\n");
-        printf("*** so that the correct libraries are found at run-time))\n");
-      }
-    }
-  return 1;
-}
-],, no_glib=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"])
-       CFLAGS="$ac_save_CFLAGS"
-       LIBS="$ac_save_LIBS"
-     fi
-  fi
-  if test "x$no_glib" = x ; then
-     AC_MSG_RESULT(yes (version $glib_config_major_version.$glib_config_minor_version.$glib_config_micro_version))
-     ifelse([$2], , :, [$2])     
-  else
-     AC_MSG_RESULT(no)
-     if test "$PKG_CONFIG" = "no" ; then
-       echo "*** A new enough version of pkg-config was not found."
-       echo "*** See http://www.freedesktop.org/software/pkgconfig/"
-     else
-       if test -f conf.glibtest ; then
-        :
-       else
-          echo "*** Could not run GLIB test program, checking why..."
-          ac_save_CFLAGS="$CFLAGS"
-          ac_save_LIBS="$LIBS"
-          CFLAGS="$CFLAGS $GLIB_CFLAGS"
-          LIBS="$LIBS $GLIB_LIBS"
-          AC_TRY_LINK([
-#include <glib.h>
-#include <stdio.h>
-],      [ return ((glib_major_version) || (glib_minor_version) || (glib_micro_version)); ],
-        [ echo "*** The test program compiled, but did not run. This usually means"
-          echo "*** that the run-time linker is not finding GLIB or finding the wrong"
-          echo "*** version of GLIB. If it is not finding GLIB, you'll need to set your"
-          echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
-          echo "*** to the installed location  Also, make sure you have run ldconfig if that"
-          echo "*** is required on your system"
-	  echo "***"
-          echo "*** If you have an old version installed, it is best to remove it, although"
-          echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH" ],
-        [ echo "*** The test program failed to compile or link. See the file config.log for the"
-          echo "*** exact error that occured. This usually means GLIB is incorrectly installed."])
-          CFLAGS="$ac_save_CFLAGS"
-          LIBS="$ac_save_LIBS"
-       fi
-     fi
-     GLIB_CFLAGS=""
-     GLIB_LIBS=""
-     GLIB_GENMARSHAL=""
-     GOBJECT_QUERY=""
-     GLIB_MKENUMS=""
-     GLIB_COMPILE_RESOURCES=""
-     ifelse([$3], , :, [$3])
-  fi
-  AC_SUBST(GLIB_CFLAGS)
-  AC_SUBST(GLIB_LIBS)
-  AC_SUBST(GLIB_GENMARSHAL)
-  AC_SUBST(GOBJECT_QUERY)
-  AC_SUBST(GLIB_MKENUMS)
-  AC_SUBST(GLIB_COMPILE_RESOURCES)
-  rm -f conf.glibtest
-])
-
-# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
-# serial 1 (pkg-config-0.24)
-# 
-# Copyright © 2004 Scott James Remnant <scott at netsplit.com>.
-#
-# 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 to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# PKG_PROG_PKG_CONFIG([MIN-VERSION])
-# ----------------------------------
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; if not, write to the Free Software
+dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+dnl 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if you
+dnl distribute this file as part of a program that contains a
+dnl configuration script generated by Autoconf, you may include it under
+dnl the same distribution terms that you use for the rest of that
+dnl program.
+
+dnl PKG_PREREQ(MIN-VERSION)
+dnl -----------------------
+dnl Since: 0.29
+dnl
+dnl Verify that the version of the pkg-config macros are at least
+dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's
+dnl installed version of pkg-config, this checks the developer's version
+dnl of pkg.m4 when generating configure.
+dnl
+dnl To ensure that this macro is defined, also add:
+dnl m4_ifndef([PKG_PREREQ],
+dnl     [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])])
+dnl
+dnl See the "Since" comment for each macro you use to see what version
+dnl of the macros you require.
+m4_defun([PKG_PREREQ],
+[m4_define([PKG_MACROS_VERSION], [0.29])
+m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1,
+    [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])])
+])dnl PKG_PREREQ
+
+dnl PKG_PROG_PKG_CONFIG([MIN-VERSION])
+dnl ----------------------------------
+dnl Since: 0.16
+dnl
+dnl Search for the pkg-config tool and set the PKG_CONFIG variable to
+dnl first found in the path. Checks that the version of pkg-config found
+dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is
+dnl used since that's the first version where most current features of
+dnl pkg-config existed.
 AC_DEFUN([PKG_PROG_PKG_CONFIG],
 [m4_pattern_forbid([^_?PKG_[A-Z_]+$])
 m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
@@ -279,18 +98,19 @@ if test -n "$PKG_CONFIG"; then
 		PKG_CONFIG=""
 	fi
 fi[]dnl
-])# PKG_PROG_PKG_CONFIG
+])dnl PKG_PROG_PKG_CONFIG
 
-# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-#
-# Check to see whether a particular set of modules exists.  Similar
-# to PKG_CHECK_MODULES(), but does not set variables or print errors.
-#
-# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-# only at the first occurence in configure.ac, so if the first place
-# it's called might be skipped (such as if it is within an "if", you
-# have to call PKG_CHECK_EXISTS manually
-# --------------------------------------------------------------
+dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------------------------------
+dnl Since: 0.18
+dnl
+dnl Check to see whether a particular set of modules exists. Similar to
+dnl PKG_CHECK_MODULES(), but does not set variables or print errors.
+dnl
+dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+dnl only at the first occurence in configure.ac, so if the first place
+dnl it's called might be skipped (such as if it is within an "if", you
+dnl have to call PKG_CHECK_EXISTS manually
 AC_DEFUN([PKG_CHECK_EXISTS],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
 if test -n "$PKG_CONFIG" && \
@@ -300,8 +120,10 @@ m4_ifvaln([$3], [else
   $3])dnl
 fi])
 
-# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
-# ---------------------------------------------
+dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+dnl ---------------------------------------------
+dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting
+dnl pkg_failed based on the result.
 m4_define([_PKG_CONFIG],
 [if test -n "$$1"; then
     pkg_cv_[]$1="$$1"
@@ -313,10 +135,11 @@ m4_define([_PKG_CONFIG],
  else
     pkg_failed=untried
 fi[]dnl
-])# _PKG_CONFIG
+])dnl _PKG_CONFIG
 
-# _PKG_SHORT_ERRORS_SUPPORTED
-# -----------------------------
+dnl _PKG_SHORT_ERRORS_SUPPORTED
+dnl ---------------------------
+dnl Internal check to see if pkg-config supports short errors.
 AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])
 if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
@@ -324,19 +147,17 @@ if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
 else
         _pkg_short_errors_supported=no
 fi[]dnl
-])# _PKG_SHORT_ERRORS_SUPPORTED
+])dnl _PKG_SHORT_ERRORS_SUPPORTED
 
 
-# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
-# [ACTION-IF-NOT-FOUND])
-#
-#
-# Note that if there is a possibility the first call to
-# PKG_CHECK_MODULES might not happen, you should be sure to include an
-# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
-#
-#
-# --------------------------------------------------------------
+dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl --------------------------------------------------------------
+dnl Since: 0.4.0
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES might not happen, you should be sure to include an
+dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
 AC_DEFUN([PKG_CHECK_MODULES],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
 AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
@@ -390,9 +211,92 @@ else
         AC_MSG_RESULT([yes])
 	$3
 fi[]dnl
-])# PKG_CHECK_MODULES
+])dnl PKG_CHECK_MODULES
+
+
+dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl ---------------------------------------------------------------------
+dnl Since: 0.29
+dnl
+dnl Checks for existence of MODULES and gathers its build flags with
+dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags
+dnl and VARIABLE-PREFIX_LIBS from --libs.
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to
+dnl include an explicit call to PKG_PROG_PKG_CONFIG in your
+dnl configure.ac.
+AC_DEFUN([PKG_CHECK_MODULES_STATIC],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+_save_PKG_CONFIG=$PKG_CONFIG
+PKG_CONFIG="$PKG_CONFIG --static"
+PKG_CHECK_MODULES($@)
+PKG_CONFIG=$_save_PKG_CONFIG[]dnl
+])dnl PKG_CHECK_MODULES_STATIC
+
+
+dnl PKG_INSTALLDIR([DIRECTORY])
+dnl -------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable pkgconfigdir as the location where a module
+dnl should install pkg-config .pc files. By default the directory is
+dnl $libdir/pkgconfig, but the default can be changed by passing
+dnl DIRECTORY. The user can override through the --with-pkgconfigdir
+dnl parameter.
+AC_DEFUN([PKG_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([pkgconfigdir],
+    [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
+    [with_pkgconfigdir=]pkg_default)
+AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+])dnl PKG_INSTALLDIR
+
+
+dnl PKG_NOARCH_INSTALLDIR([DIRECTORY])
+dnl --------------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable noarch_pkgconfigdir as the location where a
+dnl module should install arch-independent pkg-config .pc files. By
+dnl default the directory is $datadir/pkgconfig, but the default can be
+dnl changed by passing DIRECTORY. The user can override through the
+dnl --with-noarch-pkgconfigdir parameter.
+AC_DEFUN([PKG_NOARCH_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([noarch-pkgconfigdir],
+    [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
+    [with_noarch_pkgconfigdir=]pkg_default)
+AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+])dnl PKG_NOARCH_INSTALLDIR
+
+
+dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
+dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------
+dnl Since: 0.28
+dnl
+dnl Retrieves the value of the pkg-config variable for the given module.
+AC_DEFUN([PKG_CHECK_VAR],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
+
+_PKG_CONFIG([$1], [variable="][$3]["], [$2])
+AS_VAR_COPY([$1], [pkg_cv_][$1])
+
+AS_VAR_IF([$1], [""], [$5], [$4])dnl
+])dnl PKG_CHECK_VAR
 
-# Copyright (C) 2002-2013 Free Software Foundation, Inc.
+# Copyright (C) 2002-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -404,10 +308,10 @@ fi[]dnl
 # generated from the m4 files accompanying Automake X.Y.
 # (This private macro should not be called outside this file.)
 AC_DEFUN([AM_AUTOMAKE_VERSION],
-[am__api_version='1.14'
+[am__api_version='1.15'
 dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
 dnl require some minimum version.  Point them to the right macro.
-m4_if([$1], [1.14.1], [],
+m4_if([$1], [1.15], [],
       [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
 ])
 
@@ -423,12 +327,12 @@ m4_define([_AM_AUTOCONF_VERSION], [])
 # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
 # This function is AC_REQUIREd by AM_INIT_AUTOMAKE.
 AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
-[AM_AUTOMAKE_VERSION([1.14.1])dnl
+[AM_AUTOMAKE_VERSION([1.15])dnl
 m4_ifndef([AC_AUTOCONF_VERSION],
   [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
 _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))])
 
-# Copyright (C) 2011-2013 Free Software Foundation, Inc.
+# Copyright (C) 2011-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -490,7 +394,7 @@ AC_SUBST([AR])dnl
 
 # AM_AUX_DIR_EXPAND                                         -*- Autoconf -*-
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -535,15 +439,14 @@ AC_SUBST([AR])dnl
 # configured tree to be moved without reconfiguration.
 
 AC_DEFUN([AM_AUX_DIR_EXPAND],
-[dnl Rely on autoconf to set up CDPATH properly.
-AC_PREREQ([2.50])dnl
-# expand $ac_aux_dir to an absolute path
-am_aux_dir=`cd $ac_aux_dir && pwd`
+[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
+# Expand $ac_aux_dir to an absolute path.
+am_aux_dir=`cd "$ac_aux_dir" && pwd`
 ])
 
 # AM_CONDITIONAL                                            -*- Autoconf -*-
 
-# Copyright (C) 1997-2013 Free Software Foundation, Inc.
+# Copyright (C) 1997-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -574,7 +477,7 @@ AC_CONFIG_COMMANDS_PRE(
 Usually this means the macro was only invoked conditionally.]])
 fi])])
 
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Copyright (C) 1999-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -765,7 +668,7 @@ _AM_SUBST_NOTMAKE([am__nodep])dnl
 
 # Generate code to set up dependency tracking.              -*- Autoconf -*-
 
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Copyright (C) 1999-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -841,7 +744,7 @@ AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
 
 # Do all the work for Automake.                             -*- Autoconf -*-
 
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+# Copyright (C) 1996-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -931,8 +834,8 @@ AC_REQUIRE([AC_PROG_MKDIR_P])dnl
 # <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
 # <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
 AC_SUBST([mkdir_p], ['$(MKDIR_P)'])
-# We need awk for the "check" target.  The system "awk" is bad on
-# some platforms.
+# We need awk for the "check" target (and possibly the TAP driver).  The
+# system "awk" is bad on some platforms.
 AC_REQUIRE([AC_PROG_AWK])dnl
 AC_REQUIRE([AC_PROG_MAKE_SET])dnl
 AC_REQUIRE([AM_SET_LEADING_DOT])dnl
@@ -1006,6 +909,9 @@ END
     AC_MSG_ERROR([Your 'rm' program is bad, sorry.])
   fi
 fi
+dnl The trailing newline in this macro's definition is deliberate, for
+dnl backward compatibility and to allow trailing 'dnl'-style comments
+dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841.
 ])
 
 dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion.  Do not
@@ -1035,7 +941,7 @@ for _am_header in $config_headers :; do
 done
 echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1046,7 +952,7 @@ echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_co
 # Define $install_sh.
 AC_DEFUN([AM_PROG_INSTALL_SH],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-if test x"${install_sh}" != xset; then
+if test x"${install_sh+set}" != xset; then
   case $am_aux_dir in
   *\ * | *\	*)
     install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
@@ -1056,7 +962,7 @@ if test x"${install_sh}" != xset; then
 fi
 AC_SUBST([install_sh])])
 
-# Copyright (C) 2003-2013 Free Software Foundation, Inc.
+# Copyright (C) 2003-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1077,7 +983,7 @@ AC_SUBST([am__leading_dot])])
 
 # Check to see how 'make' treats includes.	            -*- Autoconf -*-
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1127,7 +1033,7 @@ rm -f confinc confmf
 
 # Fake the existence of programs that GNU maintainers use.  -*- Autoconf -*-
 
-# Copyright (C) 1997-2013 Free Software Foundation, Inc.
+# Copyright (C) 1997-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1166,7 +1072,7 @@ fi
 
 # Helper functions for option handling.                     -*- Autoconf -*-
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1195,7 +1101,7 @@ AC_DEFUN([_AM_SET_OPTIONS],
 AC_DEFUN([_AM_IF_OPTION],
 [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
 
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Copyright (C) 1999-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1242,7 +1148,7 @@ AC_LANG_POP([C])])
 # For backward compatibility.
 AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])])
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1261,7 +1167,7 @@ AC_DEFUN([AM_RUN_LOG],
 
 # Check to make sure that the build environment is sane.    -*- Autoconf -*-
 
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+# Copyright (C) 1996-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1342,7 +1248,7 @@ AC_CONFIG_COMMANDS_PRE(
 rm -f conftest.file
 ])
 
-# Copyright (C) 2009-2013 Free Software Foundation, Inc.
+# Copyright (C) 2009-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1402,7 +1308,7 @@ AC_SUBST([AM_BACKSLASH])dnl
 _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl
 ])
 
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
+# Copyright (C) 2001-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1430,7 +1336,7 @@ fi
 INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
 AC_SUBST([INSTALL_STRIP_PROGRAM])])
 
-# Copyright (C) 2006-2013 Free Software Foundation, Inc.
+# Copyright (C) 2006-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1449,7 +1355,7 @@ AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)])
 
 # Check how to create a tarball.                            -*- Autoconf -*-
 
-# Copyright (C) 2004-2013 Free Software Foundation, Inc.
+# Copyright (C) 2004-2014 Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -1580,8 +1486,9 @@ AC_SUBST([am__tar])
 AC_SUBST([am__untar])
 ]) # _AM_PROG_TAR
 
-m4_include([autostuff/libtool.m4])
-m4_include([autostuff/ltoptions.m4])
-m4_include([autostuff/ltsugar.m4])
-m4_include([autostuff/ltversion.m4])
-m4_include([autostuff/lt~obsolete.m4])
+m4_include([m4/libtool.m4])
+m4_include([m4/ltoptions.m4])
+m4_include([m4/ltsugar.m4])
+m4_include([m4/ltversion.m4])
+m4_include([m4/lt~obsolete.m4])
+m4_include([m4/sigrok.m4])
diff --git a/autostuff/ar-lib b/autostuff/ar-lib
index fe2301e..463b9ec 100755
--- a/autostuff/ar-lib
+++ b/autostuff/ar-lib
@@ -4,7 +4,7 @@
 me=ar-lib
 scriptversion=2012-03-01.08; # UTC
 
-# Copyright (C) 2010-2013 Free Software Foundation, Inc.
+# Copyright (C) 2010-2014 Free Software Foundation, Inc.
 # Written by Peter Rosin <peda at lysator.liu.se>.
 #
 # This program is free software; you can redistribute it and/or modify
diff --git a/autostuff/compile b/autostuff/compile
index 531136b..a85b723 100755
--- a/autostuff/compile
+++ b/autostuff/compile
@@ -3,7 +3,7 @@
 
 scriptversion=2012-10-14.11; # UTC
 
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Copyright (C) 1999-2014 Free Software Foundation, Inc.
 # Written by Tom Tromey <tromey at cygnus.com>.
 #
 # This program is free software; you can redistribute it and/or modify
diff --git a/autostuff/config.guess b/autostuff/config.guess
index b79252d..2e9ad7f 100755
--- a/autostuff/config.guess
+++ b/autostuff/config.guess
@@ -1,8 +1,8 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright 1992-2013 Free Software Foundation, Inc.
+#   Copyright 1992-2016 Free Software Foundation, Inc.
 
-timestamp='2013-06-10'
+timestamp='2016-10-02'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -24,12 +24,12 @@ timestamp='2013-06-10'
 # program.  This Exception is an additional permission under section 7
 # of the GNU General Public License, version 3 ("GPLv3").
 #
-# Originally written by Per Bothner.
+# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
 #
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
 #
-# Please send patches with a ChangeLog entry to config-patches at gnu.org.
+# Please send patches to <config-patches at gnu.org>.
 
 
 me=`echo "$0" | sed -e 's,.*/,,'`
@@ -50,7 +50,7 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright 1992-2013 Free Software Foundation, Inc.
+Copyright 1992-2016 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -149,7 +149,7 @@ Linux|GNU|GNU/*)
 	LIBC=gnu
 	#endif
 	EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
 	;;
 esac
 
@@ -168,19 +168,29 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	# Note: NetBSD doesn't particularly care about the vendor
 	# portion of the name.  We always set it to "unknown".
 	sysctl="sysctl -n hw.machine_arch"
-	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
-	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
+	    /sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || \
+	    echo unknown)`
 	case "${UNAME_MACHINE_ARCH}" in
 	    armeb) machine=armeb-unknown ;;
 	    arm*) machine=arm-unknown ;;
 	    sh3el) machine=shl-unknown ;;
 	    sh3eb) machine=sh-unknown ;;
 	    sh5el) machine=sh5le-unknown ;;
+	    earmv*)
+		arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
+		endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'`
+		machine=${arch}${endian}-unknown
+		;;
 	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
-	# to ELF recently, or will in the future.
+	# to ELF recently (or will in the future) and ABI.
 	case "${UNAME_MACHINE_ARCH}" in
+	    earm*)
+		os=netbsdelf
+		;;
 	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
 		eval $set_cc_for_build
 		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
@@ -197,6 +207,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		os=netbsd
 		;;
 	esac
+	# Determine ABI tags.
+	case "${UNAME_MACHINE_ARCH}" in
+	    earm*)
+		expr='s/^earmv[0-9]/-eabi/;s/eb$//'
+		abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"`
+		;;
+	esac
 	# The OS release
 	# Debian GNU/NetBSD machines have a different userland, and
 	# thus, need a distinct triplet. However, they do not need
@@ -207,13 +224,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		release='-gnu'
 		;;
 	    *)
-		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2`
 		;;
 	esac
 	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
 	# contains redundant information, the shorter form:
 	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
-	echo "${machine}-${os}${release}"
+	echo "${machine}-${os}${release}${abi}"
 	exit ;;
     *:Bitrig:*:*)
 	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
@@ -223,6 +240,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
 	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
 	exit ;;
+    *:LibertyBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE}
+	exit ;;
     *:ekkoBSD:*:*)
 	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
 	exit ;;
@@ -235,6 +256,9 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     *:MirBSD:*:*)
 	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
 	exit ;;
+    *:Sortix:*:*)
+	echo ${UNAME_MACHINE}-unknown-sortix
+	exit ;;
     alpha:OSF1:*:*)
 	case $UNAME_RELEASE in
 	*4.0)
@@ -251,42 +275,42 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
 	case "$ALPHA_CPU_TYPE" in
 	    "EV4 (21064)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "EV4.5 (21064)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "LCA4 (21066/21068)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "EV5 (21164)")
-		UNAME_MACHINE="alphaev5" ;;
+		UNAME_MACHINE=alphaev5 ;;
 	    "EV5.6 (21164A)")
-		UNAME_MACHINE="alphaev56" ;;
+		UNAME_MACHINE=alphaev56 ;;
 	    "EV5.6 (21164PC)")
-		UNAME_MACHINE="alphapca56" ;;
+		UNAME_MACHINE=alphapca56 ;;
 	    "EV5.7 (21164PC)")
-		UNAME_MACHINE="alphapca57" ;;
+		UNAME_MACHINE=alphapca57 ;;
 	    "EV6 (21264)")
-		UNAME_MACHINE="alphaev6" ;;
+		UNAME_MACHINE=alphaev6 ;;
 	    "EV6.7 (21264A)")
-		UNAME_MACHINE="alphaev67" ;;
+		UNAME_MACHINE=alphaev67 ;;
 	    "EV6.8CB (21264C)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.8AL (21264B)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.8CX (21264D)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.9A (21264/EV69A)")
-		UNAME_MACHINE="alphaev69" ;;
+		UNAME_MACHINE=alphaev69 ;;
 	    "EV7 (21364)")
-		UNAME_MACHINE="alphaev7" ;;
+		UNAME_MACHINE=alphaev7 ;;
 	    "EV7.9 (21364A)")
-		UNAME_MACHINE="alphaev79" ;;
+		UNAME_MACHINE=alphaev79 ;;
 	esac
 	# A Pn.n version is a patched version.
 	# A Vn.n version is a released version.
 	# A Tn.n version is a released field test version.
 	# A Xn.n version is an unreleased experimental baselevel.
 	# 1.2 uses "1.2" for uname -r.
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
 	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
 	exitcode=$?
 	trap '' 0
@@ -359,16 +383,16 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	exit ;;
     i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
 	eval $set_cc_for_build
-	SUN_ARCH="i386"
+	SUN_ARCH=i386
 	# If there is a compiler, see if it is configured for 64-bit objects.
 	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
 	# This test works for both compilers.
-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
 	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		(CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
 		grep IS_64BIT_ARCH >/dev/null
 	    then
-		SUN_ARCH="x86_64"
+		SUN_ARCH=x86_64
 	    fi
 	fi
 	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
@@ -393,7 +417,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	exit ;;
     sun*:*:4.2BSD:*)
 	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
-	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3
 	case "`/bin/arch`" in
 	    sun3)
 		echo m68k-sun-sunos${UNAME_RELEASE}
@@ -579,8 +603,9 @@ EOF
 	else
 		IBM_ARCH=powerpc
 	fi
-	if [ -x /usr/bin/oslevel ] ; then
-		IBM_REV=`/usr/bin/oslevel`
+	if [ -x /usr/bin/lslpp ] ; then
+		IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+			   awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
 	else
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
@@ -617,13 +642,13 @@ EOF
 		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
 		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
 		    case "${sc_cpu_version}" in
-		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
-		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+		      523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0
+		      528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1
 		      532)                      # CPU_PA_RISC2_0
 			case "${sc_kernel_bits}" in
-			  32) HP_ARCH="hppa2.0n" ;;
-			  64) HP_ARCH="hppa2.0w" ;;
-			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+			  32) HP_ARCH=hppa2.0n ;;
+			  64) HP_ARCH=hppa2.0w ;;
+			  '') HP_ARCH=hppa2.0 ;;   # HP-UX 10.20
 			esac ;;
 		    esac
 		fi
@@ -662,11 +687,11 @@ EOF
 		    exit (0);
 		}
 EOF
-		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
 		    test -z "$HP_ARCH" && HP_ARCH=hppa
 		fi ;;
 	esac
-	if [ ${HP_ARCH} = "hppa2.0w" ]
+	if [ ${HP_ARCH} = hppa2.0w ]
 	then
 	    eval $set_cc_for_build
 
@@ -679,12 +704,12 @@ EOF
 	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
 	    # => hppa64-hp-hpux11.23
 
-	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+	    if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) |
 		grep -q __LP64__
 	    then
-		HP_ARCH="hppa2.0w"
+		HP_ARCH=hppa2.0w
 	    else
-		HP_ARCH="hppa64"
+		HP_ARCH=hppa64
 	    fi
 	fi
 	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
@@ -789,14 +814,14 @@ EOF
 	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
 	exit ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
-	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
+	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
 	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
 	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
 	exit ;;
     5000:UNIX_System_V:4.*:*)
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'`
 	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
 	exit ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
@@ -826,7 +851,7 @@ EOF
     *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
 	exit ;;
-    i*:MSYS*:*)
+    *:MSYS*:*)
 	echo ${UNAME_MACHINE}-pc-msys
 	exit ;;
     i*:windows32*:*)
@@ -878,7 +903,7 @@ EOF
 	exit ;;
     *:GNU/*:*:*)
 	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
 	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
@@ -901,7 +926,7 @@ EOF
 	  EV68*) UNAME_MACHINE=alphaev68 ;;
 	esac
 	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+	if test "$?" = 0 ; then LIBC=gnulibc1 ; fi
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     arc:Linux:*:* | arceb:Linux:*:*)
@@ -932,6 +957,9 @@ EOF
     crisv32:Linux:*:*)
 	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
+    e2k:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
     frv:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
@@ -944,6 +972,9 @@ EOF
     ia64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
+    k1om:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
     m32r*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
@@ -969,10 +1000,13 @@ EOF
 	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
 	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
 	;;
-    or1k:Linux:*:*)
+    mips64el:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
-    or32:Linux:*:*)
+    openrisc*:Linux:*:*)
+	echo or1k-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:* | or1k*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     padre:Linux:*:*)
@@ -1001,6 +1035,9 @@ EOF
     ppcle:Linux:*:*)
 	echo powerpcle-unknown-linux-${LIBC}
 	exit ;;
+    riscv32:Linux:*:* | riscv64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
 	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
 	exit ;;
@@ -1020,7 +1057,7 @@ EOF
 	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
 	exit ;;
     x86_64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
 	exit ;;
     xtensa*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
@@ -1099,7 +1136,7 @@ EOF
 	# uname -m prints for DJGPP always 'pc', but it prints nothing about
 	# the processor, so we play safe by assuming i586.
 	# Note: whatever this is, it MUST be the same as what config.sub
-	# prints for the "djgpp" host, or else GDB configury will decide that
+	# prints for the "djgpp" host, or else GDB configure will decide that
 	# this is a cross-build.
 	echo i586-pc-msdosdjgpp
 	exit ;;
@@ -1248,6 +1285,9 @@ EOF
     SX-8R:SUPER-UX:*:*)
 	echo sx8r-nec-superux${UNAME_RELEASE}
 	exit ;;
+    SX-ACE:SUPER-UX:*:*)
+	echo sxace-nec-superux${UNAME_RELEASE}
+	exit ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
 	exit ;;
@@ -1260,22 +1300,32 @@ EOF
 	if test "$UNAME_PROCESSOR" = unknown ; then
 	    UNAME_PROCESSOR=powerpc
 	fi
-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-	    if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		grep IS_64BIT_ARCH >/dev/null
-	    then
-		case $UNAME_PROCESSOR in
-		    i386) UNAME_PROCESSOR=x86_64 ;;
-		    powerpc) UNAME_PROCESSOR=powerpc64 ;;
-		esac
+	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+	    if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
+		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		    (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+		    grep IS_64BIT_ARCH >/dev/null
+		then
+		    case $UNAME_PROCESSOR in
+			i386) UNAME_PROCESSOR=x86_64 ;;
+			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		    esac
+		fi
 	    fi
+	elif test "$UNAME_PROCESSOR" = i386 ; then
+	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+	    # that puts up a graphical alert prompting to install
+	    # developer tools.  Any system running Mac OS X 10.7 or
+	    # later (Darwin 11 and later) is required to have a 64-bit
+	    # processor. This is not true of the ARM version of Darwin
+	    # that Apple uses in portable devices.
+	    UNAME_PROCESSOR=x86_64
 	fi
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
 	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
 	UNAME_PROCESSOR=`uname -p`
-	if test "$UNAME_PROCESSOR" = "x86"; then
+	if test "$UNAME_PROCESSOR" = x86; then
 		UNAME_PROCESSOR=i386
 		UNAME_MACHINE=pc
 	fi
@@ -1306,7 +1356,7 @@ EOF
 	# "uname -m" is not consistent, so use $cputype instead. 386
 	# is converted to i386 for consistency with other x86
 	# operating systems.
-	if test "$cputype" = "386"; then
+	if test "$cputype" = 386; then
 	    UNAME_MACHINE=i386
 	else
 	    UNAME_MACHINE="$cputype"
@@ -1348,7 +1398,7 @@ EOF
 	echo i386-pc-xenix
 	exit ;;
     i*86:skyos:*:*)
-	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'`
 	exit ;;
     i*86:rdos:*:*)
 	echo ${UNAME_MACHINE}-pc-rdos
@@ -1359,171 +1409,25 @@ EOF
     x86_64:VMkernel:*:*)
 	echo ${UNAME_MACHINE}-unknown-esx
 	exit ;;
-esac
-
-eval $set_cc_for_build
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
-  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
-     I don't know....  */
-  printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
-  printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
-	"4"
-#else
-	""
-#endif
-	); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix\n"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
-  printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
-  int version;
-  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
-  if (version < 4)
-    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
-  else
-    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
-  exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
-  printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
-  printf ("ns32k-encore-mach\n"); exit (0);
-#else
-  printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
-  printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
-  printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
-  printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
-    struct utsname un;
-
-    uname(&un);
-
-    if (strncmp(un.version, "V2", 2) == 0) {
-	printf ("i386-sequent-ptx2\n"); exit (0);
-    }
-    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
-	printf ("i386-sequent-ptx1\n"); exit (0);
-    }
-    printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-# if !defined (ultrix)
-#  include <sys/param.h>
-#  if defined (BSD)
-#   if BSD == 43
-      printf ("vax-dec-bsd4.3\n"); exit (0);
-#   else
-#    if BSD == 199006
-      printf ("vax-dec-bsd4.3reno\n"); exit (0);
-#    else
-      printf ("vax-dec-bsd\n"); exit (0);
-#    endif
-#   endif
-#  else
-    printf ("vax-dec-bsd\n"); exit (0);
-#  endif
-# else
-    printf ("vax-dec-ultrix\n"); exit (0);
-# endif
-#endif
-
-#if defined (alliant) && defined (i860)
-  printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
-  exit (1);
-}
-EOF
-
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
-	{ echo "$SYSTEM_NAME"; exit; }
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
-    case `getsysinfo -f cpu_type` in
-    c1*)
-	echo c1-convex-bsd
-	exit ;;
-    c2*)
-	if getsysinfo -f scalar_acc
-	then echo c32-convex-bsd
-	else echo c2-convex-bsd
-	fi
-	exit ;;
-    c34*)
-	echo c34-convex-bsd
-	exit ;;
-    c38*)
-	echo c38-convex-bsd
-	exit ;;
-    c4*)
-	echo c4-convex-bsd
+    amd64:Isilon\ OneFS:*:*)
+	echo x86_64-unknown-onefs
 	exit ;;
-    esac
-fi
+esac
 
 cat >&2 <<EOF
 $0: unable to guess system type
 
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
+This script (version $timestamp), has failed to recognize the
+operating system you are using. If your script is old, overwrite
+config.guess and config.sub with the latest versions from:
 
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
 and
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches at gnu.org> in order to provide the needed
-information to handle your system.
+If $0 has already been updated, send the following data and any
+information you think might be pertinent to config-patches at gnu.org to
+provide the necessary information to handle your system.
 
 config.guess timestamp = $timestamp
 
diff --git a/autostuff/config.sub b/autostuff/config.sub
index 9633db7..dd2ca93 100755
--- a/autostuff/config.sub
+++ b/autostuff/config.sub
@@ -1,8 +1,8 @@
 #! /bin/sh
 # Configuration validation subroutine script.
-#   Copyright 1992-2013 Free Software Foundation, Inc.
+#   Copyright 1992-2016 Free Software Foundation, Inc.
 
-timestamp='2013-08-10'
+timestamp='2016-11-04'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -25,7 +25,7 @@ timestamp='2013-08-10'
 # of the GNU General Public License, version 3 ("GPLv3").
 
 
-# Please send patches with a ChangeLog entry to config-patches at gnu.org.
+# Please send patches to <config-patches at gnu.org>.
 #
 # Configuration subroutine to validate and canonicalize a configuration type.
 # Supply the specified configuration type as an argument.
@@ -33,7 +33,7 @@ timestamp='2013-08-10'
 # Otherwise, we print the canonical config type on stdout and succeed.
 
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
@@ -53,8 +53,7 @@ timestamp='2013-08-10'
 me=`echo "$0" | sed -e 's,.*/,,'`
 
 usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
-       $0 [OPTION] ALIAS
+Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS
 
 Canonicalize a configuration name.
 
@@ -68,7 +67,7 @@ Report bugs and patches to <config-patches at gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright 1992-2013 Free Software Foundation, Inc.
+Copyright 1992-2016 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -117,8 +116,8 @@ maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
   nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
   linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
-  knetbsd*-gnu* | netbsd*-gnu* | \
-  kopensolaris*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
+  kopensolaris*-gnu* | cloudabi*-eabi* | \
   storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
@@ -255,16 +254,18 @@ case $basic_machine in
 	| arc | arceb \
 	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
 	| avr | avr32 \
+	| ba \
 	| be32 | be64 \
 	| bfin \
 	| c4x | c8051 | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| epiphany \
-	| fido | fr30 | frv \
+	| e2k | epiphany \
+	| fido | fr30 | frv | ft32 \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| hexagon \
 	| i370 | i860 | i960 | ia64 \
 	| ip2k | iq2000 \
+	| k1om \
 	| le32 | le64 \
 	| lm32 \
 	| m32c | m32r | m32rle | m68000 | m68k | m88k \
@@ -282,8 +283,10 @@ case $basic_machine in
 	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa32r6 | mipsisa32r6el \
 	| mipsisa64 | mipsisa64el \
 	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64r6 | mipsisa64r6el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
 	| mipsr5900 | mipsr5900el \
@@ -295,14 +298,15 @@ case $basic_machine in
 	| nds32 | nds32le | nds32be \
 	| nios | nios2 | nios2eb | nios2el \
 	| ns16k | ns32k \
-	| open8 \
-	| or1k | or32 \
+	| open8 | or1k | or1knd | or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle \
+	| pru \
 	| pyramid \
+	| riscv32 | riscv64 \
 	| rl78 | rx \
 	| score \
-	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
 	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
 	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
@@ -310,6 +314,7 @@ case $basic_machine in
 	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
 	| ubicom32 \
 	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+	| visium \
 	| we32k \
 	| x86 | xc16x | xstormy16 | xtensa \
 	| z8k | z80)
@@ -324,7 +329,10 @@ case $basic_machine in
 	c6x)
 		basic_machine=tic6x-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+	leon|leon[3-9])
+		basic_machine=sparc-$basic_machine
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
@@ -369,18 +377,20 @@ case $basic_machine in
 	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
 	| avr-* | avr32-* \
+	| ba-* \
 	| be32-* | be64-* \
 	| bfin-* | bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* \
 	| c8051-* | clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
-	| elxsi-* \
+	| e2k-* | elxsi-* \
 	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| hexagon-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
 	| ip2k-* | iq2000-* \
+	| k1om-* \
 	| le32-* | le64-* \
 	| lm32-* \
 	| m32c-* | m32r-* | m32rle-* \
@@ -400,8 +410,10 @@ case $basic_machine in
 	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa32r6-* | mipsisa32r6el-* \
 	| mipsisa64-* | mipsisa64el-* \
 	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64r6-* | mipsisa64r6el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
 	| mipsr5900-* | mipsr5900el-* \
@@ -413,16 +425,19 @@ case $basic_machine in
 	| nios-* | nios2-* | nios2eb-* | nios2el-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
 	| open8-* \
+	| or1k*-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+	| pru-* \
 	| pyramid-* \
+	| riscv32-* | riscv64-* \
 	| rl78-* | romp-* | rs6000-* | rx-* \
 	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
 	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
 	| sparclite-* \
-	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \
 	| tahoe-* \
 	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
 	| tile*-* \
@@ -430,6 +445,7 @@ case $basic_machine in
 	| ubicom32-* \
 	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
 	| vax-* \
+	| visium-* \
 	| we32k-* \
 	| x86-* | x86_64-* | xc16x-* | xps100-* \
 	| xstormy16-* | xtensa*-* \
@@ -506,6 +522,9 @@ case $basic_machine in
 		basic_machine=i386-pc
 		os=-aros
 		;;
+	asmjs)
+		basic_machine=asmjs-unknown
+		;;
 	aux)
 		basic_machine=m68k-apple
 		os=-aux
@@ -626,6 +645,14 @@ case $basic_machine in
 		basic_machine=m68k-bull
 		os=-sysv3
 		;;
+	e500v[12])
+		basic_machine=powerpc-unknown
+		os=$os"spe"
+		;;
+	e500v[12]-*)
+		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=$os"spe"
+		;;
 	ebmon29k)
 		basic_machine=a29k-amd
 		os=-ebmon
@@ -767,6 +794,9 @@ case $basic_machine in
 		basic_machine=m68k-isi
 		os=-sysv
 		;;
+	leon-*|leon[3-9]-*)
+		basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
+		;;
 	m68knommu)
 		basic_machine=m68k-unknown
 		os=-linux
@@ -822,6 +852,10 @@ case $basic_machine in
 		basic_machine=powerpc-unknown
 		os=-morphos
 		;;
+	moxiebox)
+		basic_machine=moxie-unknown
+		os=-moxiebox
+		;;
 	msdos)
 		basic_machine=i386-pc
 		os=-msdos
@@ -998,7 +1032,7 @@ case $basic_machine in
 	ppc-* | ppcbe-*)
 		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	ppcle | powerpclittle | ppc-le | powerpc-little)
+	ppcle | powerpclittle)
 		basic_machine=powerpcle-unknown
 		;;
 	ppcle-* | powerpclittle-*)
@@ -1008,7 +1042,7 @@ case $basic_machine in
 		;;
 	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+	ppc64le | powerpc64little)
 		basic_machine=powerpc64le-unknown
 		;;
 	ppc64le-* | powerpc64little-*)
@@ -1354,27 +1388,28 @@ case $os in
 	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
 	      | -sym* | -kopensolaris* | -plan9* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* | -aros* \
+	      | -aos* | -aros* | -cloudabi* | -sortix* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
 	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
-	      | -bitrig* | -openbsd* | -solidbsd* \
+	      | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \
 	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
 	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
 	      | -chorusos* | -chorusrdb* | -cegcc* \
 	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+	      | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
 	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
 	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \
+	      | -onefs* | -tirtos* | -phoenix* | -fuchsia*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1506,6 +1541,8 @@ case $os in
 		;;
 	-nacl*)
 		;;
+	-ios)
+		;;
 	-none)
 		;;
 	*)
@@ -1592,9 +1629,6 @@ case $basic_machine in
 	mips*-*)
 		os=-elf
 		;;
-	or1k-*)
-		os=-elf
-		;;
 	or32-*)
 		os=-coff
 		;;
diff --git a/autostuff/depcomp b/autostuff/depcomp
index 4ebd5b3..fc98710 100755
--- a/autostuff/depcomp
+++ b/autostuff/depcomp
@@ -3,7 +3,7 @@
 
 scriptversion=2013-05-30.07; # UTC
 
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
+# Copyright (C) 1999-2014 Free Software Foundation, Inc.
 
 # 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
diff --git a/autostuff/install-sh b/autostuff/install-sh
index 377bb86..59990a1 100755
--- a/autostuff/install-sh
+++ b/autostuff/install-sh
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-11-20.07; # UTC
+scriptversion=2014-09-12.12; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -41,19 +41,15 @@ scriptversion=2011-11-20.07; # UTC
 # This script is compatible with the BSD install script, but was written
 # from scratch.
 
+tab='	'
 nl='
 '
-IFS=" ""	$nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,17 +64,6 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
@@ -97,7 +82,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -137,46 +122,57 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-	shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-	case $mode in
-	  *' '* | *'	'* | *'
-'*	  | *'*'* | *'?'* | *'['*)
-	    echo "$0: invalid mode: $mode" >&2
-	    exit 1;;
-	esac
-	shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-	shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
-    -t) dst_arg=$2
-	# Protect names problematic for 'test' and other utilities.
-	case $dst_arg in
-	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
-	esac
-	shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)	shift
-	break;;
+    --) shift
+        break;;
 
-    -*)	echo "$0: invalid option: $1" >&2
-	exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -208,6 +204,15 @@ if test $# -eq 0; then
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -223,16 +228,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-	u_plus_rw=
+        u_plus_rw=
       else
-	u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-	u_plus_rw=
+        u_plus_rw=
       else
-	u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -269,41 +274,15 @@ do
     # If destination is a directory, append the input filename; won't work
     # if double slashes aren't ignored.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-	echo "$0: $dst_arg: Is a directory" >&2
-	exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
       dst=$dstdir/`basename "$src"`
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-	(dirname "$dst") 2>/dev/null ||
-	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	     X"$dst" : 'X\(//\)[^/]' \| \
-	     X"$dst" : 'X\(//\)$' \| \
-	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-	echo X"$dst" |
-	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\/\)[^/].*/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\/\)$/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\).*/{
-		   s//\1/
-		   q
-		 }
-		 s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
@@ -314,74 +293,81 @@ do
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-	# Create intermediate dirs using mode 755 as modified by the umask.
-	# This is like FreeBSD 'install' as of 1997-10-28.
-	umask=`umask`
-	case $stripcmd.$umask in
-	  # Optimize common cases.
-	  *[2367][2367]) mkdir_umask=$umask;;
-	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-	  *[0-7])
-	    mkdir_umask=`expr $umask + 22 \
-	      - $umask % 100 % 40 + $umask % 20 \
-	      - $umask % 10 % 4 + $umask % 2
-	    `;;
-	  *) mkdir_umask=$umask,go-w;;
-	esac
-
-	# With -d, create the new directory with the user-specified mode.
-	# Otherwise, rely on $mkdir_umask.
-	if test -n "$dir_arg"; then
-	  mkdir_mode=-m$mode
-	else
-	  mkdir_mode=
-	fi
-
-	posix_mkdir=false
-	case $umask in
-	  *[123567][0-7][0-7])
-	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
-	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-	    ;;
-	  *)
-	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-	    if (umask $mkdir_umask &&
-		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-	    then
-	      if test -z "$dir_arg" || {
-		   # Check for POSIX incompatibilities with -m.
-		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-		   # other-writable bit of parent directory when it shouldn't.
-		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
-		   case $ls_ld_tmpdir in
-		     d????-?r-*) different_mode=700;;
-		     d????-?--*) different_mode=755;;
-		     *) false;;
-		   esac &&
-		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-		   }
-		 }
-	      then posix_mkdir=:
-	      fi
-	      rmdir "$tmpdir/d" "$tmpdir"
-	    else
-	      # Remove any dirs left behind by ancient mkdir implementations.
-	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-	    fi
-	    trap '' 0;;
-	esac;;
+        # Create intermediate dirs using mode 755 as modified by the umask.
+        # This is like FreeBSD 'install' as of 1997-10-28.
+        umask=`umask`
+        case $stripcmd.$umask in
+          # Optimize common cases.
+          *[2367][2367]) mkdir_umask=$umask;;
+          .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+          *[0-7])
+            mkdir_umask=`expr $umask + 22 \
+              - $umask % 100 % 40 + $umask % 20 \
+              - $umask % 10 % 4 + $umask % 2
+            `;;
+          *) mkdir_umask=$umask,go-w;;
+        esac
+
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+        case $umask in
+          *[123567][0-7][0-7])
+            # POSIX mkdir -p sets u+wx bits regardless of umask, which
+            # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+            ;;
+          *)
+            # $RANDOM is not portable (e.g. dash);  use it when possible to
+            # lower collision chance
+            tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+            trap 'ret=$?; rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+            # As "mkdir -p" follows symlinks and we work in /tmp possibly;  so
+            # create the $tmpdir first (and fail if unsuccessful) to make sure
+            # that nobody tries to guess the $tmpdir name.
+            if (umask $mkdir_umask &&
+                $mkdirprog $mkdir_mode "$tmpdir" &&
+                exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+            then
+              if test -z "$dir_arg" || {
+                   # Check for POSIX incompatibilities with -m.
+                   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+                   # other-writable bit of parent directory when it shouldn't.
+                   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+                   test_tmpdir="$tmpdir/a"
+                   ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+                   case $ls_ld_tmpdir in
+                     d????-?r-*) different_mode=700;;
+                     d????-?--*) different_mode=755;;
+                     *) false;;
+                   esac &&
+                   $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                     ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+                   }
+                 }
+              then posix_mkdir=:
+              fi
+              rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
+            else
+              # Remove any dirs left behind by ancient mkdir implementations.
+              rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
+            fi
+            trap '' 0;;
+        esac;;
     esac
 
     if
       $posix_mkdir && (
-	umask $mkdir_umask &&
-	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
@@ -391,53 +377,51 @@ do
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-	/*) prefix='/';;
-	[-=\(\)!]*) prefix='./';;
-	*)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-	test X"$d" = X && continue
-
-	prefix=$prefix$d
-	if test -d "$prefix"; then
-	  prefixes=
-	else
-	  if $posix_mkdir; then
-	    (umask=$mkdir_umask &&
-	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-	    # Don't fail if two instances are running concurrently.
-	    test -d "$prefix" || exit 1
-	  else
-	    case $prefix in
-	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-	      *) qprefix=$prefix;;
-	    esac
-	    prefixes="$prefixes '$qprefix'"
-	  fi
-	fi
-	prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask=$mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-	# Don't fail if two instances are running concurrently.
-	(umask $mkdir_umask &&
-	 eval "\$doit_exec \$mkdirprog $prefixes") ||
-	  test -d "$dstdir" || exit 1
-	obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -472,15 +456,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -493,24 +474,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-	# Now remove or move aside any old file at destination location.
-	# We try this two ways since rm can't unlink itself on some
-	# systems and the destination file might be busy for other
-	# reasons.  In this case, the final cleanup might fail but the new
-	# file should still install successfully.
-	{
-	  test ! -f "$dst" ||
-	  $doit $rmcmd -f "$dst" 2>/dev/null ||
-	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-	  } ||
-	  { echo "$0: cannot unlink or rename $dst" >&2
-	    (exit 1); exit 1
-	  }
-	} &&
-
-	# Now rename the file to the real destination.
-	$doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
diff --git a/autostuff/ltmain.sh b/autostuff/ltmain.sh
index bb5fa02..a736cf9 100644
--- a/autostuff/ltmain.sh
+++ b/autostuff/ltmain.sh
@@ -1,9 +1,12 @@
+#! /bin/sh
+## DO NOT EDIT - This file generated from ./build-aux/ltmain.in
+##               by inline-source v2014-01-03.01
 
-# libtool (GNU libtool) 2.4.2
+# libtool (GNU libtool) 2.4.6
+# Provide generalized library-building support services.
 # Written by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
 
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
-# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
+# Copyright (C) 1996-2015 Free Software Foundation, Inc.
 # This is free software; see the source for copying conditions.  There is NO
 # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
@@ -23,881 +26,2112 @@
 # General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html,
-# or obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Usage: $progname [OPTION]... [MODE-ARG]...
-#
-# Provide generalized library-building support services.
-#
-#       --config             show all configuration variables
-#       --debug              enable verbose shell tracing
-#   -n, --dry-run            display commands without modifying any files
-#       --features           display basic configuration information and exit
-#       --mode=MODE          use operation mode MODE
-#       --preserve-dup-deps  don't remove duplicate dependency libraries
-#       --quiet, --silent    don't print informational messages
-#       --no-quiet, --no-silent
-#                            print informational messages (default)
-#       --no-warn            don't display warning messages
-#       --tag=TAG            use configuration variables from tag TAG
-#   -v, --verbose            print more informational messages than default
-#       --no-verbose         don't print the extra informational messages
-#       --version            print version information
-#   -h, --help, --help-all   print short, long, or detailed help message
-#
-# MODE must be one of the following:
-#
-#         clean              remove files from the build directory
-#         compile            compile a source file into a libtool object
-#         execute            automatically set library path, then run a program
-#         finish             complete the installation of libtool libraries
-#         install            install libraries or executables
-#         link               create a library or an executable
-#         uninstall          remove libraries from an installed directory
-#
-# MODE-ARGS vary depending on the MODE.  When passed as first option,
-# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
-# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
-#
-# When reporting a bug, please describe a test case to reproduce it and
-# include the following information:
-#
-#         host-triplet:	$host
-#         shell:		$SHELL
-#         compiler:		$LTCC
-#         compiler flags:		$LTCFLAGS
-#         linker:		$LD (gnu? $with_gnu_ld)
-#         $progname:	(GNU libtool) 2.4.2 Debian-2.4.2-1.7
-#         automake:	$automake_version
-#         autoconf:	$autoconf_version
-#
-# Report bugs to <bug-libtool at gnu.org>.
-# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
-# General help using GNU software: <http://www.gnu.org/gethelp/>.
 
 PROGRAM=libtool
 PACKAGE=libtool
-VERSION="2.4.2 Debian-2.4.2-1.7"
-TIMESTAMP=""
-package_revision=1.3337
+VERSION="2.4.6 Debian-2.4.6-2"
+package_revision=2.4.6
 
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+
+## ------ ##
+## Usage. ##
+## ------ ##
+
+# Run './libtool --help' for help with using this script from the
+# command line.
+
+
+## ------------------------------- ##
+## User overridable command paths. ##
+## ------------------------------- ##
+
+# After configure completes, it has a better idea of some of the
+# shell tools we need than the defaults used by the functions shared
+# with bootstrap, so set those here where they can still be over-
+# ridden by the user, but otherwise take precedence.
+
+: ${AUTOCONF="autoconf"}
+: ${AUTOMAKE="automake"}
+
+
+## -------------------------- ##
+## Source external libraries. ##
+## -------------------------- ##
+
+# Much of our low-level functionality needs to be sourced from external
+# libraries, which are installed to $pkgauxdir.
+
+# Set a version string for this script.
+scriptversion=2015-01-20.17; # UTC
+
+# General shell script boiler plate, and helper functions.
+# Written by Gary V. Vaughan, 2004
+
+# Copyright (C) 2004-2015 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# 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 3 of the License, or
+# (at your option) any later version.
+
+# As a special exception to the GNU General Public License, if you distribute
+# this file as part of a program or library that is built using GNU Libtool,
+# you may include this file under the same distribution terms that you use
+# for the rest of that program.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNES 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, see <http://www.gnu.org/licenses/>.
+
+# Please report bugs or propose patches to gary at gnu.org.
+
+
+## ------ ##
+## Usage. ##
+## ------ ##
+
+# Evaluate this file near the top of your script to gain access to
+# the functions and variables defined here:
+#
+#   . `echo "$0" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh
+#
+# If you need to override any of the default environment variable
+# settings, do that before evaluating this file.
+
+
+## -------------------- ##
+## Shell normalisation. ##
+## -------------------- ##
+
+# Some shells need a little help to be as Bourne compatible as possible.
+# Before doing anything else, make sure all that help has been provided!
+
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
   emulate sh
   NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
   setopt NO_GLOB_SUBST
 else
-  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac
 fi
-BIN_SH=xpg4; export BIN_SH # for Tru64
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-$1
-_LTECHO_EOF'
-}
 
-# NLS nuisances: We save the old values to restore during execute mode.
-lt_user_locale=
-lt_safe_locale=
-for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+# NLS nuisances: We save the old values in case they are required later.
+_G_user_locale=
+_G_safe_locale=
+for _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
 do
-  eval "if test \"\${$lt_var+set}\" = set; then
-          save_$lt_var=\$$lt_var
-          $lt_var=C
-	  export $lt_var
-	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
-	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
+  eval "if test set = \"\${$_G_var+set}\"; then
+          save_$_G_var=\$$_G_var
+          $_G_var=C
+	  export $_G_var
+	  _G_user_locale=\"$_G_var=\\\$save_\$_G_var; \$_G_user_locale\"
+	  _G_safe_locale=\"$_G_var=C; \$_G_safe_locale\"
 	fi"
 done
-LC_ALL=C
-LANGUAGE=C
-export LANGUAGE LC_ALL
 
-$lt_unset CDPATH
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
+# Make sure IFS has a sensible default
+sp=' '
+nl='
+'
+IFS="$sp	$nl"
+
+# There are apparently some retarded systems that use ';' as a PATH separator!
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
 
-# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
-# is ksh but when the shell is invoked as "sh" and the current value of
-# the _XPG environment variable is not equal to 1 (one), the special
-# positional parameter $0, within a function call, is the name of the
-# function.
-progpath="$0"
 
 
+## ------------------------- ##
+## Locate command utilities. ##
+## ------------------------- ##
+
+
+# func_executable_p FILE
+# ----------------------
+# Check that FILE is an executable regular file.
+func_executable_p ()
+{
+    test -f "$1" && test -x "$1"
+}
+
+
+# func_path_progs PROGS_LIST CHECK_FUNC [PATH]
+# --------------------------------------------
+# Search for either a program that responds to --version with output
+# containing "GNU", or else returned by CHECK_FUNC otherwise, by
+# trying all the directories in PATH with each of the elements of
+# PROGS_LIST.
+#
+# CHECK_FUNC should accept the path to a candidate program, and
+# set $func_check_prog_result if it truncates its output less than
+# $_G_path_prog_max characters.
+func_path_progs ()
+{
+    _G_progs_list=$1
+    _G_check_func=$2
+    _G_PATH=${3-"$PATH"}
+
+    _G_path_prog_max=0
+    _G_path_prog_found=false
+    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}
+    for _G_dir in $_G_PATH; do
+      IFS=$_G_save_IFS
+      test -z "$_G_dir" && _G_dir=.
+      for _G_prog_name in $_G_progs_list; do
+        for _exeext in '' .EXE; do
+          _G_path_prog=$_G_dir/$_G_prog_name$_exeext
+          func_executable_p "$_G_path_prog" || continue
+          case `"$_G_path_prog" --version 2>&1` in
+            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;
+            *)     $_G_check_func $_G_path_prog
+		   func_path_progs_result=$func_check_prog_result
+		   ;;
+          esac
+          $_G_path_prog_found && break 3
+        done
+      done
+    done
+    IFS=$_G_save_IFS
+    test -z "$func_path_progs_result" && {
+      echo "no acceptable sed could be found in \$PATH" >&2
+      exit 1
+    }
+}
+
+
+# We want to be able to use the functions in this file before configure
+# has figured out where the best binaries are kept, which means we have
+# to search for them ourselves - except when the results are already set
+# where we skip the searches.
+
+# Unless the user overrides by setting SED, search the path for either GNU
+# sed, or the sed that truncates its output the least.
+test -z "$SED" && {
+  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
+  for _G_i in 1 2 3 4 5 6 7; do
+    _G_sed_script=$_G_sed_script$nl$_G_sed_script
+  done
+  echo "$_G_sed_script" 2>/dev/null | sed 99q >conftest.sed
+  _G_sed_script=
+
+  func_check_prog_sed ()
+  {
+    _G_path_prog=$1
+
+    _G_count=0
+    printf 0123456789 >conftest.in
+    while :
+    do
+      cat conftest.in conftest.in >conftest.tmp
+      mv conftest.tmp conftest.in
+      cp conftest.in conftest.nl
+      echo '' >> conftest.nl
+      "$_G_path_prog" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break
+      diff conftest.out conftest.nl >/dev/null 2>&1 || break
+      _G_count=`expr $_G_count + 1`
+      if test "$_G_count" -gt "$_G_path_prog_max"; then
+        # Best one so far, save it but keep looking for a better one
+        func_check_prog_result=$_G_path_prog
+        _G_path_prog_max=$_G_count
+      fi
+      # 10*(2^10) chars as input seems more than enough
+      test 10 -lt "$_G_count" && break
+    done
+    rm -f conftest.in conftest.tmp conftest.nl conftest.out
+  }
+
+  func_path_progs "sed gsed" func_check_prog_sed $PATH:/usr/xpg4/bin
+  rm -f conftest.sed
+  SED=$func_path_progs_result
+}
+
+
+# Unless the user overrides by setting GREP, search the path for either GNU
+# grep, or the grep that truncates its output the least.
+test -z "$GREP" && {
+  func_check_prog_grep ()
+  {
+    _G_path_prog=$1
+
+    _G_count=0
+    _G_path_prog_max=0
+    printf 0123456789 >conftest.in
+    while :
+    do
+      cat conftest.in conftest.in >conftest.tmp
+      mv conftest.tmp conftest.in
+      cp conftest.in conftest.nl
+      echo 'GREP' >> conftest.nl
+      "$_G_path_prog" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break
+      diff conftest.out conftest.nl >/dev/null 2>&1 || break
+      _G_count=`expr $_G_count + 1`
+      if test "$_G_count" -gt "$_G_path_prog_max"; then
+        # Best one so far, save it but keep looking for a better one
+        func_check_prog_result=$_G_path_prog
+        _G_path_prog_max=$_G_count
+      fi
+      # 10*(2^10) chars as input seems more than enough
+      test 10 -lt "$_G_count" && break
+    done
+    rm -f conftest.in conftest.tmp conftest.nl conftest.out
+  }
+
+  func_path_progs "grep ggrep" func_check_prog_grep $PATH:/usr/xpg4/bin
+  GREP=$func_path_progs_result
+}
+
+
+## ------------------------------- ##
+## User overridable command paths. ##
+## ------------------------------- ##
+
+# All uppercase variable names are used for environment variables.  These
+# variables can be overridden by the user before calling a script that
+# uses them if a suitable command of that name is not already available
+# in the command search PATH.
 
 : ${CP="cp -f"}
-test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
+: ${ECHO="printf %s\n"}
+: ${EGREP="$GREP -E"}
+: ${FGREP="$GREP -F"}
+: ${LN_S="ln -s"}
 : ${MAKE="make"}
 : ${MKDIR="mkdir"}
 : ${MV="mv -f"}
 : ${RM="rm -f"}
 : ${SHELL="${CONFIG_SHELL-/bin/sh}"}
-: ${Xsed="$SED -e 1s/^X//"}
-
-# Global variables:
-EXIT_SUCCESS=0
-EXIT_FAILURE=1
-EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
-EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
-
-exit_status=$EXIT_SUCCESS
-
-# Make sure IFS has a sensible default
-lt_nl='
-'
-IFS=" 	$lt_nl"
 
-dirname="s,/[^/]*$,,"
-basename="s,^.*/,,"
 
-# func_dirname file append nondir_replacement
-# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
-# otherwise set result to NONDIR_REPLACEMENT.
-func_dirname ()
-{
-    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
-    if test "X$func_dirname_result" = "X${1}"; then
-      func_dirname_result="${3}"
-    else
-      func_dirname_result="$func_dirname_result${2}"
-    fi
-} # func_dirname may be replaced by extended shell implementation
+## -------------------- ##
+## Useful sed snippets. ##
+## -------------------- ##
 
+sed_dirname='s|/[^/]*$||'
+sed_basename='s|^.*/||'
 
-# func_basename file
-func_basename ()
-{
-    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
-} # func_basename may be replaced by extended shell implementation
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='s|\([`"$\\]\)|\\\1|g'
 
+# Same as above, but do not quote variable references.
+sed_double_quote_subst='s/\(["`\\]\)/\\\1/g'
 
-# func_dirname_and_basename file append nondir_replacement
-# perform func_basename and func_dirname in a single function
-# call:
-#   dirname:  Compute the dirname of FILE.  If nonempty,
-#             add APPEND to the result, otherwise set result
-#             to NONDIR_REPLACEMENT.
-#             value returned in "$func_dirname_result"
-#   basename: Compute filename of FILE.
-#             value retuned in "$func_basename_result"
-# Implementation must be kept synchronized with func_dirname
-# and func_basename. For efficiency, we do not delegate to
-# those functions but instead duplicate the functionality here.
-func_dirname_and_basename ()
-{
-    # Extract subdirectory from the argument.
-    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
-    if test "X$func_dirname_result" = "X${1}"; then
-      func_dirname_result="${3}"
-    else
-      func_dirname_result="$func_dirname_result${2}"
-    fi
-    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
-} # func_dirname_and_basename may be replaced by extended shell implementation
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex='s|[].[^$\\*\/]|\\&|g'
 
+# Sed substitution that converts a w32 file name or path
+# that contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+
+# Re-'\' parameter expansions in output of sed_double_quote_subst that
+# were '\'-ed in input to the same.  If an odd number of '\' preceded a
+# '$' in input to sed_double_quote_subst, that '$' was protected from
+# expansion.  Since each input '\' is now two '\'s, look for any number
+# of runs of four '\'s followed by two '\'s and then a '$'.  '\' that '$'.
+_G_bs='\\'
+_G_bs2='\\\\'
+_G_bs4='\\\\\\\\'
+_G_dollar='\$'
+sed_double_backslash="\
+  s/$_G_bs4/&\\
+/g
+  s/^$_G_bs2$_G_dollar/$_G_bs&/
+  s/\\([^$_G_bs]\\)$_G_bs2$_G_dollar/\\1$_G_bs2$_G_bs$_G_dollar/g
+  s/\n//g"
 
-# func_stripname prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-# func_strip_suffix prefix name
-func_stripname ()
-{
-    case ${2} in
-      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
-      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
-    esac
-} # func_stripname may be replaced by extended shell implementation
 
+## ----------------- ##
+## Global variables. ##
+## ----------------- ##
 
-# These SED scripts presuppose an absolute path with a trailing slash.
-pathcar='s,^/\([^/]*\).*$,\1,'
-pathcdr='s,^/[^/]*,,'
-removedotparts=':dotsl
-		s@/\./@/@g
-		t dotsl
-		s,/\.$,/,'
-collapseslashes='s@/\{1,\}@/@g'
-finalslash='s,/*$,/,'
+# Except for the global variables explicitly listed below, the following
+# functions in the '^func_' namespace, and the '^require_' namespace
+# variables initialised in the 'Resource management' section, sourcing
+# this file will not pollute your global namespace with anything
+# else. There's no portable way to scope variables in Bourne shell
+# though, so actually running these functions will sometimes place
+# results into a variable named after the function, and often use
+# temporary variables in the '^_G_' namespace. If you are careful to
+# avoid using those namespaces casually in your sourcing script, things
+# should continue to work as you expect. And, of course, you can freely
+# overwrite any of the functions or variables defined here before
+# calling anything to customize them.
 
-# func_normal_abspath PATH
-# Remove doubled-up and trailing slashes, "." path components,
-# and cancel out any ".." path components in PATH after making
-# it an absolute path.
-#             value returned in "$func_normal_abspath_result"
-func_normal_abspath ()
-{
-  # Start from root dir and reassemble the path.
-  func_normal_abspath_result=
-  func_normal_abspath_tpath=$1
-  func_normal_abspath_altnamespace=
-  case $func_normal_abspath_tpath in
-    "")
-      # Empty path, that just means $cwd.
-      func_stripname '' '/' "`pwd`"
-      func_normal_abspath_result=$func_stripname_result
-      return
-    ;;
-    # The next three entries are used to spot a run of precisely
-    # two leading slashes without using negated character classes;
-    # we take advantage of case's first-match behaviour.
-    ///*)
-      # Unusual form of absolute path, do nothing.
-    ;;
-    //*)
-      # Not necessarily an ordinary path; POSIX reserves leading '//'
-      # and for example Cygwin uses it to access remote file shares
-      # over CIFS/SMB, so we conserve a leading double slash if found.
-      func_normal_abspath_altnamespace=/
-    ;;
-    /*)
-      # Absolute path, do nothing.
-    ;;
-    *)
-      # Relative path, prepend $cwd.
-      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
-    ;;
-  esac
-  # Cancel out all the simple stuff to save iterations.  We also want
-  # the path to end with a slash for ease of parsing, so make sure
-  # there is one (and only one) here.
-  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
-  while :; do
-    # Processed it all yet?
-    if test "$func_normal_abspath_tpath" = / ; then
-      # If we ascended to the root using ".." the result may be empty now.
-      if test -z "$func_normal_abspath_result" ; then
-        func_normal_abspath_result=/
-      fi
-      break
-    fi
-    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$pathcar"`
-    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$pathcdr"`
-    # Figure out what to do with it
-    case $func_normal_abspath_tcomponent in
-      "")
-        # Trailing empty path component, ignore it.
-      ;;
-      ..)
-        # Parent dir; strip last assembled component from result.
-        func_dirname "$func_normal_abspath_result"
-        func_normal_abspath_result=$func_dirname_result
-      ;;
-      *)
-        # Actual path component, append it.
-        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
-      ;;
-    esac
-  done
-  # Restore leading double-slash if one was found on entry.
-  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
-}
+EXIT_SUCCESS=0
+EXIT_FAILURE=1
+EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
+EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
 
-# func_relative_path SRCDIR DSTDIR
-# generates a relative path from SRCDIR to DSTDIR, with a trailing
-# slash if non-empty, suitable for immediately appending a filename
-# without needing to append a separator.
-#             value returned in "$func_relative_path_result"
-func_relative_path ()
-{
-  func_relative_path_result=
-  func_normal_abspath "$1"
-  func_relative_path_tlibdir=$func_normal_abspath_result
-  func_normal_abspath "$2"
-  func_relative_path_tbindir=$func_normal_abspath_result
-
-  # Ascend the tree starting from libdir
-  while :; do
-    # check if we have found a prefix of bindir
-    case $func_relative_path_tbindir in
-      $func_relative_path_tlibdir)
-        # found an exact match
-        func_relative_path_tcancelled=
-        break
-        ;;
-      $func_relative_path_tlibdir*)
-        # found a matching prefix
-        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
-        func_relative_path_tcancelled=$func_stripname_result
-        if test -z "$func_relative_path_result"; then
-          func_relative_path_result=.
-        fi
-        break
-        ;;
-      *)
-        func_dirname $func_relative_path_tlibdir
-        func_relative_path_tlibdir=${func_dirname_result}
-        if test "x$func_relative_path_tlibdir" = x ; then
-          # Have to descend all the way to the root!
-          func_relative_path_result=../$func_relative_path_result
-          func_relative_path_tcancelled=$func_relative_path_tbindir
-          break
-        fi
-        func_relative_path_result=../$func_relative_path_result
-        ;;
-    esac
-  done
+# Allow overriding, eg assuming that you follow the convention of
+# putting '$debug_cmd' at the start of all your functions, you can get
+# bash to show function call trace with:
+#
+#    debug_cmd='eval echo "${FUNCNAME[0]} $*" >&2' bash your-script-name
+debug_cmd=${debug_cmd-":"}
+exit_cmd=:
 
-  # Now calculate path; take care to avoid doubling-up slashes.
-  func_stripname '' '/' "$func_relative_path_result"
-  func_relative_path_result=$func_stripname_result
-  func_stripname '/' '/' "$func_relative_path_tcancelled"
-  if test "x$func_stripname_result" != x ; then
-    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
-  fi
+# By convention, finish your script with:
+#
+#    exit $exit_status
+#
+# so that you can set exit_status to non-zero if you want to indicate
+# something went wrong during execution without actually bailing out at
+# the point of failure.
+exit_status=$EXIT_SUCCESS
 
-  # Normalisation. If bindir is libdir, return empty string,
-  # else relative path ending with a slash; either way, target
-  # file name can be directly appended.
-  if test ! -z "$func_relative_path_result"; then
-    func_stripname './' '' "$func_relative_path_result/"
-    func_relative_path_result=$func_stripname_result
-  fi
-}
+# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
+# is ksh but when the shell is invoked as "sh" and the current value of
+# the _XPG environment variable is not equal to 1 (one), the special
+# positional parameter $0, within a function call, is the name of the
+# function.
+progpath=$0
 
-# The name of this program:
-func_dirname_and_basename "$progpath"
-progname=$func_basename_result
+# The name of this program.
+progname=`$ECHO "$progpath" |$SED "$sed_basename"`
 
-# Make sure we have an absolute path for reexecution:
+# Make sure we have an absolute progpath for reexecution:
 case $progpath in
   [\\/]*|[A-Za-z]:\\*) ;;
   *[\\/]*)
-     progdir=$func_dirname_result
+     progdir=`$ECHO "$progpath" |$SED "$sed_dirname"`
      progdir=`cd "$progdir" && pwd`
-     progpath="$progdir/$progname"
+     progpath=$progdir/$progname
      ;;
   *)
-     save_IFS="$IFS"
+     _G_IFS=$IFS
      IFS=${PATH_SEPARATOR-:}
      for progdir in $PATH; do
-       IFS="$save_IFS"
+       IFS=$_G_IFS
        test -x "$progdir/$progname" && break
      done
-     IFS="$save_IFS"
+     IFS=$_G_IFS
      test -n "$progdir" || progdir=`pwd`
-     progpath="$progdir/$progname"
+     progpath=$progdir/$progname
      ;;
 esac
 
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed="${SED}"' -e 1s/^X//'
-sed_quote_subst='s/\([`"$\\]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\(["`\\]\)/\\\1/g'
 
-# Sed substitution that turns a string into a regex matching for the
-# string literally.
-sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
+## ----------------- ##
+## Standard options. ##
+## ----------------- ##
 
-# Sed substitution that converts a w32 file name or path
-# which contains forward slashes, into one that contains
-# (escaped) backslashes.  A very naive implementation.
-lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-
-# Re-`\' parameter expansions in output of double_quote_subst that were
-# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
-# in input to double_quote_subst, that '$' was protected from expansion.
-# Since each input `\' is now two `\'s, look for any number of runs of
-# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
-bs='\\'
-bs2='\\\\'
-bs4='\\\\\\\\'
-dollar='\$'
-sed_double_backslash="\
-  s/$bs4/&\\
-/g
-  s/^$bs2$dollar/$bs&/
-  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
-  s/\n//g"
+# The following options affect the operation of the functions defined
+# below, and should be set appropriately depending on run-time para-
+# meters passed on the command line.
 
-# Standard options:
 opt_dry_run=false
-opt_help=false
 opt_quiet=false
 opt_verbose=false
-opt_warning=:
 
-# func_echo arg...
-# Echo program name prefixed message, along with the current mode
-# name if it has been set yet.
-func_echo ()
-{
-    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
-}
+# Categories 'all' and 'none' are always available.  Append any others
+# you will pass as the first argument to func_warning from your own
+# code.
+warning_categories=
 
-# func_verbose arg...
-# Echo program name prefixed message in verbose mode only.
-func_verbose ()
-{
-    $opt_verbose && func_echo ${1+"$@"}
+# By default, display warnings according to 'opt_warning_types'.  Set
+# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to
+# treat the next displayed warning as a fatal error.
+warning_func=func_warn_and_continue
 
-    # A bug in bash halts the script if the last line of a function
-    # fails when set -e is in force, so we need another command to
-    # work around that:
-    :
-}
+# Set to 'all' to display all warnings, 'none' to suppress all
+# warnings, or a space delimited list of some subset of
+# 'warning_categories' to display only the listed warnings.
+opt_warning_types=all
 
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO "$*"
-}
 
-# func_error arg...
-# Echo program name prefixed message to standard error.
-func_error ()
-{
-    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
-}
+## -------------------- ##
+## Resource management. ##
+## -------------------- ##
 
-# func_warning arg...
-# Echo program name prefixed warning message to standard error.
-func_warning ()
-{
-    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
+# This section contains definitions for functions that each ensure a
+# particular resource (a file, or a non-empty configuration variable for
+# example) is available, and if appropriate to extract default values
+# from pertinent package files. Call them using their associated
+# 'require_*' variable to ensure that they are executed, at most, once.
+#
+# It's entirely deliberate that calling these functions can set
+# variables that don't obey the namespace limitations obeyed by the rest
+# of this file, in order that that they be as useful as possible to
+# callers.
 
-    # bash bug again:
-    :
-}
 
-# func_fatal_error arg...
-# Echo program name prefixed message to standard error, and exit.
-func_fatal_error ()
+# require_term_colors
+# -------------------
+# Allow display of bold text on terminals that support it.
+require_term_colors=func_require_term_colors
+func_require_term_colors ()
 {
-    func_error ${1+"$@"}
-    exit $EXIT_FAILURE
-}
+    $debug_cmd
+
+    test -t 1 && {
+      # COLORTERM and USE_ANSI_COLORS environment variables take
+      # precedence, because most terminfo databases neglect to describe
+      # whether color sequences are supported.
+      test -n "${COLORTERM+set}" && : ${USE_ANSI_COLORS="1"}
+
+      if test 1 = "$USE_ANSI_COLORS"; then
+        # Standard ANSI escape sequences
+        tc_reset=''
+        tc_bold='';   tc_standout=''
+        tc_red='';   tc_green=''
+        tc_blue='';  tc_cyan=''
+      else
+        # Otherwise trust the terminfo database after all.
+        test -n "`tput sgr0 2>/dev/null`" && {
+          tc_reset=`tput sgr0`
+          test -n "`tput bold 2>/dev/null`" && tc_bold=`tput bold`
+          tc_standout=$tc_bold
+          test -n "`tput smso 2>/dev/null`" && tc_standout=`tput smso`
+          test -n "`tput setaf 1 2>/dev/null`" && tc_red=`tput setaf 1`
+          test -n "`tput setaf 2 2>/dev/null`" && tc_green=`tput setaf 2`
+          test -n "`tput setaf 4 2>/dev/null`" && tc_blue=`tput setaf 4`
+          test -n "`tput setaf 5 2>/dev/null`" && tc_cyan=`tput setaf 5`
+        }
+      fi
+    }
 
-# func_fatal_help arg...
-# Echo program name prefixed message to standard error, followed by
-# a help hint, and exit.
-func_fatal_help ()
-{
-    func_error ${1+"$@"}
-    func_fatal_error "$help"
+    require_term_colors=:
 }
-help="Try \`$progname --help' for more information."  ## default
 
 
-# func_grep expression filename
+## ----------------- ##
+## Function library. ##
+## ----------------- ##
+
+# This section contains a variety of useful functions to call in your
+# scripts. Take note of the portable wrappers for features provided by
+# some modern shells, which will fall back to slower equivalents on
+# less featureful shells.
+
+
+# func_append VAR VALUE
+# ---------------------
+# Append VALUE onto the existing contents of VAR.
+
+  # We should try to minimise forks, especially on Windows where they are
+  # unreasonably slow, so skip the feature probes when bash or zsh are
+  # being used:
+  if test set = "${BASH_VERSION+set}${ZSH_VERSION+set}"; then
+    : ${_G_HAVE_ARITH_OP="yes"}
+    : ${_G_HAVE_XSI_OPS="yes"}
+    # The += operator was introduced in bash 3.1
+    case $BASH_VERSION in
+      [12].* | 3.0 | 3.0*) ;;
+      *)
+        : ${_G_HAVE_PLUSEQ_OP="yes"}
+        ;;
+    esac
+  fi
+
+  # _G_HAVE_PLUSEQ_OP
+  # Can be empty, in which case the shell is probed, "yes" if += is
+  # useable or anything else if it does not work.
+  test -z "$_G_HAVE_PLUSEQ_OP" \
+    && (eval 'x=a; x+=" b"; test "a b" = "$x"') 2>/dev/null \
+    && _G_HAVE_PLUSEQ_OP=yes
+
+if test yes = "$_G_HAVE_PLUSEQ_OP"
+then
+  # This is an XSI compatible shell, allowing a faster implementation...
+  eval 'func_append ()
+  {
+    $debug_cmd
+
+    eval "$1+=\$2"
+  }'
+else
+  # ...otherwise fall back to using expr, which is often a shell builtin.
+  func_append ()
+  {
+    $debug_cmd
+
+    eval "$1=\$$1\$2"
+  }
+fi
+
+
+# func_append_quoted VAR VALUE
+# ----------------------------
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+if test yes = "$_G_HAVE_PLUSEQ_OP"; then
+  eval 'func_append_quoted ()
+  {
+    $debug_cmd
+
+    func_quote_for_eval "$2"
+    eval "$1+=\\ \$func_quote_for_eval_result"
+  }'
+else
+  func_append_quoted ()
+  {
+    $debug_cmd
+
+    func_quote_for_eval "$2"
+    eval "$1=\$$1\\ \$func_quote_for_eval_result"
+  }
+fi
+
+
+# func_append_uniq VAR VALUE
+# --------------------------
+# Append unique VALUE onto the existing contents of VAR, assuming
+# entries are delimited by the first character of VALUE.  For example:
+#
+#   func_append_uniq options " --another-option option-argument"
+#
+# will only append to $options if " --another-option option-argument "
+# is not already present somewhere in $options already (note spaces at
+# each end implied by leading space in second argument).
+func_append_uniq ()
+{
+    $debug_cmd
+
+    eval _G_current_value='`$ECHO $'$1'`'
+    _G_delim=`expr "$2" : '\(.\)'`
+
+    case $_G_delim$_G_current_value$_G_delim in
+      *"$2$_G_delim"*) ;;
+      *) func_append "$@" ;;
+    esac
+}
+
+
+# func_arith TERM...
+# ------------------
+# Set func_arith_result to the result of evaluating TERMs.
+  test -z "$_G_HAVE_ARITH_OP" \
+    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \
+    && _G_HAVE_ARITH_OP=yes
+
+if test yes = "$_G_HAVE_ARITH_OP"; then
+  eval 'func_arith ()
+  {
+    $debug_cmd
+
+    func_arith_result=$(( $* ))
+  }'
+else
+  func_arith ()
+  {
+    $debug_cmd
+
+    func_arith_result=`expr "$@"`
+  }
+fi
+
+
+# func_basename FILE
+# ------------------
+# Set func_basename_result to FILE with everything up to and including
+# the last / stripped.
+if test yes = "$_G_HAVE_XSI_OPS"; then
+  # If this shell supports suffix pattern removal, then use it to avoid
+  # forking. Hide the definitions single quotes in case the shell chokes
+  # on unsupported syntax...
+  _b='func_basename_result=${1##*/}'
+  _d='case $1 in
+        */*) func_dirname_result=${1%/*}$2 ;;
+        *  ) func_dirname_result=$3        ;;
+      esac'
+
+else
+  # ...otherwise fall back to using sed.
+  _b='func_basename_result=`$ECHO "$1" |$SED "$sed_basename"`'
+  _d='func_dirname_result=`$ECHO "$1"  |$SED "$sed_dirname"`
+      if test "X$func_dirname_result" = "X$1"; then
+        func_dirname_result=$3
+      else
+        func_append func_dirname_result "$2"
+      fi'
+fi
+
+eval 'func_basename ()
+{
+    $debug_cmd
+
+    '"$_b"'
+}'
+
+
+# func_dirname FILE APPEND NONDIR_REPLACEMENT
+# -------------------------------------------
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+eval 'func_dirname ()
+{
+    $debug_cmd
+
+    '"$_d"'
+}'
+
+
+# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT
+# --------------------------------------------------------
+# Perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# For efficiency, we do not delegate to the functions above but instead
+# duplicate the functionality here.
+eval 'func_dirname_and_basename ()
+{
+    $debug_cmd
+
+    '"$_b"'
+    '"$_d"'
+}'
+
+
+# func_echo ARG...
+# ----------------
+# Echo program name prefixed message.
+func_echo ()
+{
+    $debug_cmd
+
+    _G_message=$*
+
+    func_echo_IFS=$IFS
+    IFS=$nl
+    for _G_line in $_G_message; do
+      IFS=$func_echo_IFS
+      $ECHO "$progname: $_G_line"
+    done
+    IFS=$func_echo_IFS
+}
+
+
+# func_echo_all ARG...
+# --------------------
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
+
+# func_echo_infix_1 INFIX ARG...
+# ------------------------------
+# Echo program name, followed by INFIX on the first line, with any
+# additional lines not showing INFIX.
+func_echo_infix_1 ()
+{
+    $debug_cmd
+
+    $require_term_colors
+
+    _G_infix=$1; shift
+    _G_indent=$_G_infix
+    _G_prefix="$progname: $_G_infix: "
+    _G_message=$*
+
+    # Strip color escape sequences before counting printable length
+    for _G_tc in "$tc_reset" "$tc_bold" "$tc_standout" "$tc_red" "$tc_green" "$tc_blue" "$tc_cyan"
+    do
+      test -n "$_G_tc" && {
+        _G_esc_tc=`$ECHO "$_G_tc" | $SED "$sed_make_literal_regex"`
+        _G_indent=`$ECHO "$_G_indent" | $SED "s|$_G_esc_tc||g"`
+      }
+    done
+    _G_indent="$progname: "`echo "$_G_indent" | $SED 's|.| |g'`"  " ## exclude from sc_prohibit_nested_quotes
+
+    func_echo_infix_1_IFS=$IFS
+    IFS=$nl
+    for _G_line in $_G_message; do
+      IFS=$func_echo_infix_1_IFS
+      $ECHO "$_G_prefix$tc_bold$_G_line$tc_reset" >&2
+      _G_prefix=$_G_indent
+    done
+    IFS=$func_echo_infix_1_IFS
+}
+
+
+# func_error ARG...
+# -----------------
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $debug_cmd
+
+    $require_term_colors
+
+    func_echo_infix_1 "  $tc_standout${tc_red}error$tc_reset" "$*" >&2
+}
+
+
+# func_fatal_error ARG...
+# -----------------------
+# Echo program name prefixed message to standard error, and exit.
+func_fatal_error ()
+{
+    $debug_cmd
+
+    func_error "$*"
+    exit $EXIT_FAILURE
+}
+
+
+# func_grep EXPRESSION FILENAME
+# -----------------------------
 # Check whether EXPRESSION matches any line of FILENAME, without output.
 func_grep ()
 {
+    $debug_cmd
+
     $GREP "$1" "$2" >/dev/null 2>&1
 }
 
 
-# func_mkdir_p directory-path
+# func_len STRING
+# ---------------
+# Set func_len_result to the length of STRING. STRING may not
+# start with a hyphen.
+  test -z "$_G_HAVE_XSI_OPS" \
+    && (eval 'x=a/b/c;
+      test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \
+    && _G_HAVE_XSI_OPS=yes
+
+if test yes = "$_G_HAVE_XSI_OPS"; then
+  eval 'func_len ()
+  {
+    $debug_cmd
+
+    func_len_result=${#1}
+  }'
+else
+  func_len ()
+  {
+    $debug_cmd
+
+    func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len`
+  }
+fi
+
+
+# func_mkdir_p DIRECTORY-PATH
+# ---------------------------
 # Make sure the entire path to DIRECTORY-PATH is available.
 func_mkdir_p ()
 {
-    my_directory_path="$1"
-    my_dir_list=
+    $debug_cmd
 
-    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then
+    _G_directory_path=$1
+    _G_dir_list=
 
-      # Protect directory names starting with `-'
-      case $my_directory_path in
-        -*) my_directory_path="./$my_directory_path" ;;
+    if test -n "$_G_directory_path" && test : != "$opt_dry_run"; then
+
+      # Protect directory names starting with '-'
+      case $_G_directory_path in
+        -*) _G_directory_path=./$_G_directory_path ;;
       esac
 
       # While some portion of DIR does not yet exist...
-      while test ! -d "$my_directory_path"; do
+      while test ! -d "$_G_directory_path"; do
         # ...make a list in topmost first order.  Use a colon delimited
 	# list incase some portion of path contains whitespace.
-        my_dir_list="$my_directory_path:$my_dir_list"
+        _G_dir_list=$_G_directory_path:$_G_dir_list
 
         # If the last portion added has no slash in it, the list is done
-        case $my_directory_path in */*) ;; *) break ;; esac
+        case $_G_directory_path in */*) ;; *) break ;; esac
 
         # ...otherwise throw away the child directory and loop
-        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
+        _G_directory_path=`$ECHO "$_G_directory_path" | $SED -e "$sed_dirname"`
       done
-      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
+      _G_dir_list=`$ECHO "$_G_dir_list" | $SED 's|:*$||'`
 
-      save_mkdir_p_IFS="$IFS"; IFS=':'
-      for my_dir in $my_dir_list; do
-	IFS="$save_mkdir_p_IFS"
-        # mkdir can fail with a `File exist' error if two processes
+      func_mkdir_p_IFS=$IFS; IFS=:
+      for _G_dir in $_G_dir_list; do
+	IFS=$func_mkdir_p_IFS
+        # mkdir can fail with a 'File exist' error if two processes
         # try to create one of the directories concurrently.  Don't
         # stop in that case!
-        $MKDIR "$my_dir" 2>/dev/null || :
+        $MKDIR "$_G_dir" 2>/dev/null || :
       done
-      IFS="$save_mkdir_p_IFS"
+      IFS=$func_mkdir_p_IFS
 
       # Bail out if we (or some other process) failed to create a directory.
-      test -d "$my_directory_path" || \
-        func_fatal_error "Failed to create \`$1'"
+      test -d "$_G_directory_path" || \
+        func_fatal_error "Failed to create '$1'"
     fi
 }
 
 
-# func_mktempdir [string]
+# func_mktempdir [BASENAME]
+# -------------------------
 # Make a temporary directory that won't clash with other running
 # libtool processes, and avoids race conditions if possible.  If
-# given, STRING is the basename for that directory.
+# given, BASENAME is the basename for that directory.
 func_mktempdir ()
 {
-    my_template="${TMPDIR-/tmp}/${1-$progname}"
+    $debug_cmd
+
+    _G_template=${TMPDIR-/tmp}/${1-$progname}
 
-    if test "$opt_dry_run" = ":"; then
+    if test : = "$opt_dry_run"; then
       # Return a directory name, but don't create it in dry-run mode
-      my_tmpdir="${my_template}-$$"
+      _G_tmpdir=$_G_template-$$
     else
 
       # If mktemp works, use that first and foremost
-      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
+      _G_tmpdir=`mktemp -d "$_G_template-XXXXXXXX" 2>/dev/null`
 
-      if test ! -d "$my_tmpdir"; then
+      if test ! -d "$_G_tmpdir"; then
         # Failing that, at least try and use $RANDOM to avoid a race
-        my_tmpdir="${my_template}-${RANDOM-0}$$"
+        _G_tmpdir=$_G_template-${RANDOM-0}$$
 
-        save_mktempdir_umask=`umask`
+        func_mktempdir_umask=`umask`
         umask 0077
-        $MKDIR "$my_tmpdir"
-        umask $save_mktempdir_umask
+        $MKDIR "$_G_tmpdir"
+        umask $func_mktempdir_umask
       fi
 
       # If we're not in dry-run mode, bomb out on failure
-      test -d "$my_tmpdir" || \
-        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
+      test -d "$_G_tmpdir" || \
+        func_fatal_error "cannot create temporary directory '$_G_tmpdir'"
+    fi
+
+    $ECHO "$_G_tmpdir"
+}
+
+
+# func_normal_abspath PATH
+# ------------------------
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+func_normal_abspath ()
+{
+    $debug_cmd
+
+    # These SED scripts presuppose an absolute path with a trailing slash.
+    _G_pathcar='s|^/\([^/]*\).*$|\1|'
+    _G_pathcdr='s|^/[^/]*||'
+    _G_removedotparts=':dotsl
+		s|/\./|/|g
+		t dotsl
+		s|/\.$|/|'
+    _G_collapseslashes='s|/\{1,\}|/|g'
+    _G_finalslash='s|/*$|/|'
+
+    # Start from root dir and reassemble the path.
+    func_normal_abspath_result=
+    func_normal_abspath_tpath=$1
+    func_normal_abspath_altnamespace=
+    case $func_normal_abspath_tpath in
+      "")
+        # Empty path, that just means $cwd.
+        func_stripname '' '/' "`pwd`"
+        func_normal_abspath_result=$func_stripname_result
+        return
+        ;;
+      # The next three entries are used to spot a run of precisely
+      # two leading slashes without using negated character classes;
+      # we take advantage of case's first-match behaviour.
+      ///*)
+        # Unusual form of absolute path, do nothing.
+        ;;
+      //*)
+        # Not necessarily an ordinary path; POSIX reserves leading '//'
+        # and for example Cygwin uses it to access remote file shares
+        # over CIFS/SMB, so we conserve a leading double slash if found.
+        func_normal_abspath_altnamespace=/
+        ;;
+      /*)
+        # Absolute path, do nothing.
+        ;;
+      *)
+        # Relative path, prepend $cwd.
+        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
+        ;;
+    esac
+
+    # Cancel out all the simple stuff to save iterations.  We also want
+    # the path to end with a slash for ease of parsing, so make sure
+    # there is one (and only one) here.
+    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+          -e "$_G_removedotparts" -e "$_G_collapseslashes" -e "$_G_finalslash"`
+    while :; do
+      # Processed it all yet?
+      if test / = "$func_normal_abspath_tpath"; then
+        # If we ascended to the root using ".." the result may be empty now.
+        if test -z "$func_normal_abspath_result"; then
+          func_normal_abspath_result=/
+        fi
+        break
+      fi
+      func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
+          -e "$_G_pathcar"`
+      func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
+          -e "$_G_pathcdr"`
+      # Figure out what to do with it
+      case $func_normal_abspath_tcomponent in
+        "")
+          # Trailing empty path component, ignore it.
+          ;;
+        ..)
+          # Parent dir; strip last assembled component from result.
+          func_dirname "$func_normal_abspath_result"
+          func_normal_abspath_result=$func_dirname_result
+          ;;
+        *)
+          # Actual path component, append it.
+          func_append func_normal_abspath_result "/$func_normal_abspath_tcomponent"
+          ;;
+      esac
+    done
+    # Restore leading double-slash if one was found on entry.
+    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
+}
+
+
+# func_notquiet ARG...
+# --------------------
+# Echo program name prefixed message only when not in quiet mode.
+func_notquiet ()
+{
+    $debug_cmd
+
+    $opt_quiet || func_echo ${1+"$@"}
+
+    # A bug in bash halts the script if the last line of a function
+    # fails when set -e is in force, so we need another command to
+    # work around that:
+    :
+}
+
+
+# func_relative_path SRCDIR DSTDIR
+# --------------------------------
+# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.
+func_relative_path ()
+{
+    $debug_cmd
+
+    func_relative_path_result=
+    func_normal_abspath "$1"
+    func_relative_path_tlibdir=$func_normal_abspath_result
+    func_normal_abspath "$2"
+    func_relative_path_tbindir=$func_normal_abspath_result
+
+    # Ascend the tree starting from libdir
+    while :; do
+      # check if we have found a prefix of bindir
+      case $func_relative_path_tbindir in
+        $func_relative_path_tlibdir)
+          # found an exact match
+          func_relative_path_tcancelled=
+          break
+          ;;
+        $func_relative_path_tlibdir*)
+          # found a matching prefix
+          func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
+          func_relative_path_tcancelled=$func_stripname_result
+          if test -z "$func_relative_path_result"; then
+            func_relative_path_result=.
+          fi
+          break
+          ;;
+        *)
+          func_dirname $func_relative_path_tlibdir
+          func_relative_path_tlibdir=$func_dirname_result
+          if test -z "$func_relative_path_tlibdir"; then
+            # Have to descend all the way to the root!
+            func_relative_path_result=../$func_relative_path_result
+            func_relative_path_tcancelled=$func_relative_path_tbindir
+            break
+          fi
+          func_relative_path_result=../$func_relative_path_result
+          ;;
+      esac
+    done
+
+    # Now calculate path; take care to avoid doubling-up slashes.
+    func_stripname '' '/' "$func_relative_path_result"
+    func_relative_path_result=$func_stripname_result
+    func_stripname '/' '/' "$func_relative_path_tcancelled"
+    if test -n "$func_stripname_result"; then
+      func_append func_relative_path_result "/$func_stripname_result"
+    fi
+
+    # Normalisation. If bindir is libdir, return '.' else relative path.
+    if test -n "$func_relative_path_result"; then
+      func_stripname './' '' "$func_relative_path_result"
+      func_relative_path_result=$func_stripname_result
     fi
 
-    $ECHO "$my_tmpdir"
+    test -n "$func_relative_path_result" || func_relative_path_result=.
+
+    :
+}
+
+
+# func_quote_for_eval ARG...
+# --------------------------
+# Aesthetically quote ARGs to be evaled later.
+# This function returns two values:
+#   i) func_quote_for_eval_result
+#      double-quoted, suitable for a subsequent eval
+#  ii) func_quote_for_eval_unquoted_result
+#      has all characters that are still active within double
+#      quotes backslashified.
+func_quote_for_eval ()
+{
+    $debug_cmd
+
+    func_quote_for_eval_unquoted_result=
+    func_quote_for_eval_result=
+    while test 0 -lt $#; do
+      case $1 in
+        *[\\\`\"\$]*)
+	  _G_unquoted_arg=`printf '%s\n' "$1" |$SED "$sed_quote_subst"` ;;
+        *)
+          _G_unquoted_arg=$1 ;;
+      esac
+      if test -n "$func_quote_for_eval_unquoted_result"; then
+	func_append func_quote_for_eval_unquoted_result " $_G_unquoted_arg"
+      else
+        func_append func_quote_for_eval_unquoted_result "$_G_unquoted_arg"
+      fi
+
+      case $_G_unquoted_arg in
+        # Double-quote args containing shell metacharacters to delay
+        # word splitting, command substitution and variable expansion
+        # for a subsequent eval.
+        # Many Bourne shells cannot handle close brackets correctly
+        # in scan sets, so we specify it separately.
+        *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+          _G_quoted_arg=\"$_G_unquoted_arg\"
+          ;;
+        *)
+          _G_quoted_arg=$_G_unquoted_arg
+	  ;;
+      esac
+
+      if test -n "$func_quote_for_eval_result"; then
+	func_append func_quote_for_eval_result " $_G_quoted_arg"
+      else
+        func_append func_quote_for_eval_result "$_G_quoted_arg"
+      fi
+      shift
+    done
+}
+
+
+# func_quote_for_expand ARG
+# -------------------------
+# Aesthetically quote ARG to be evaled later; same as above,
+# but do not quote variable references.
+func_quote_for_expand ()
+{
+    $debug_cmd
+
+    case $1 in
+      *[\\\`\"]*)
+	_G_arg=`$ECHO "$1" | $SED \
+	    -e "$sed_double_quote_subst" -e "$sed_double_backslash"` ;;
+      *)
+        _G_arg=$1 ;;
+    esac
+
+    case $_G_arg in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting and command substitution for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        _G_arg=\"$_G_arg\"
+        ;;
+    esac
+
+    func_quote_for_expand_result=$_G_arg
+}
+
+
+# func_stripname PREFIX SUFFIX NAME
+# ---------------------------------
+# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+if test yes = "$_G_HAVE_XSI_OPS"; then
+  eval 'func_stripname ()
+  {
+    $debug_cmd
+
+    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+    # positional parameters, so assign one to ordinary variable first.
+    func_stripname_result=$3
+    func_stripname_result=${func_stripname_result#"$1"}
+    func_stripname_result=${func_stripname_result%"$2"}
+  }'
+else
+  func_stripname ()
+  {
+    $debug_cmd
+
+    case $2 in
+      .*) func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%\\\\$2\$%%"`;;
+      *)  func_stripname_result=`$ECHO "$3" | $SED -e "s%^$1%%" -e "s%$2\$%%"`;;
+    esac
+  }
+fi
+
+
+# func_show_eval CMD [FAIL_EXP]
+# -----------------------------
+# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.
+func_show_eval ()
+{
+    $debug_cmd
+
+    _G_cmd=$1
+    _G_fail_exp=${2-':'}
+
+    func_quote_for_expand "$_G_cmd"
+    eval "func_notquiet $func_quote_for_expand_result"
+
+    $opt_dry_run || {
+      eval "$_G_cmd"
+      _G_status=$?
+      if test 0 -ne "$_G_status"; then
+	eval "(exit $_G_status); $_G_fail_exp"
+      fi
+    }
+}
+
+
+# func_show_eval_locale CMD [FAIL_EXP]
+# ------------------------------------
+# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.  Use the saved locale for evaluation.
+func_show_eval_locale ()
+{
+    $debug_cmd
+
+    _G_cmd=$1
+    _G_fail_exp=${2-':'}
+
+    $opt_quiet || {
+      func_quote_for_expand "$_G_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    $opt_dry_run || {
+      eval "$_G_user_locale
+	    $_G_cmd"
+      _G_status=$?
+      eval "$_G_safe_locale"
+      if test 0 -ne "$_G_status"; then
+	eval "(exit $_G_status); $_G_fail_exp"
+      fi
+    }
+}
+
+
+# func_tr_sh
+# ----------
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+    $debug_cmd
+
+    case $1 in
+    [0-9]* | *[!a-zA-Z0-9_]*)
+      func_tr_sh_result=`$ECHO "$1" | $SED -e 's/^\([0-9]\)/_\1/' -e 's/[^a-zA-Z0-9_]/_/g'`
+      ;;
+    * )
+      func_tr_sh_result=$1
+      ;;
+    esac
+}
+
+
+# func_verbose ARG...
+# -------------------
+# Echo program name prefixed message in verbose mode only.
+func_verbose ()
+{
+    $debug_cmd
+
+    $opt_verbose && func_echo "$*"
+
+    :
+}
+
+
+# func_warn_and_continue ARG...
+# -----------------------------
+# Echo program name prefixed warning message to standard error.
+func_warn_and_continue ()
+{
+    $debug_cmd
+
+    $require_term_colors
+
+    func_echo_infix_1 "${tc_red}warning$tc_reset" "$*" >&2
+}
+
+
+# func_warning CATEGORY ARG...
+# ----------------------------
+# Echo program name prefixed warning message to standard error. Warning
+# messages can be filtered according to CATEGORY, where this function
+# elides messages where CATEGORY is not listed in the global variable
+# 'opt_warning_types'.
+func_warning ()
+{
+    $debug_cmd
+
+    # CATEGORY must be in the warning_categories list!
+    case " $warning_categories " in
+      *" $1 "*) ;;
+      *) func_internal_error "invalid warning category '$1'" ;;
+    esac
+
+    _G_category=$1
+    shift
+
+    case " $opt_warning_types " in
+      *" $_G_category "*) $warning_func ${1+"$@"} ;;
+    esac
+}
+
+
+# func_sort_ver VER1 VER2
+# -----------------------
+# 'sort -V' is not generally available.
+# Note this deviates from the version comparison in automake
+# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a
+# but this should suffice as we won't be specifying old
+# version formats or redundant trailing .0 in bootstrap.conf.
+# If we did want full compatibility then we should probably
+# use m4_version_compare from autoconf.
+func_sort_ver ()
+{
+    $debug_cmd
+
+    printf '%s\n%s\n' "$1" "$2" \
+      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n
+}
+
+# func_lt_ver PREV CURR
+# ---------------------
+# Return true if PREV and CURR are in the correct order according to
+# func_sort_ver, otherwise false.  Use it like this:
+#
+#  func_lt_ver "$prev_ver" "$proposed_ver" || func_fatal_error "..."
+func_lt_ver ()
+{
+    $debug_cmd
+
+    test "x$1" = x`func_sort_ver "$1" "$2" | $SED 1q`
+}
+
+
+# Local variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC"
+# time-stamp-time-zone: "UTC"
+# End:
+#! /bin/sh
+
+# Set a version string for this script.
+scriptversion=2014-01-07.03; # UTC
+
+# A portable, pluggable option parser for Bourne shell.
+# Written by Gary V. Vaughan, 2010
+
+# Copyright (C) 2010-2015 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+# Please report bugs or propose patches to gary at gnu.org.
+
+
+## ------ ##
+## Usage. ##
+## ------ ##
+
+# This file is a library for parsing options in your shell scripts along
+# with assorted other useful supporting features that you can make use
+# of too.
+#
+# For the simplest scripts you might need only:
+#
+#   #!/bin/sh
+#   . relative/path/to/funclib.sh
+#   . relative/path/to/options-parser
+#   scriptversion=1.0
+#   func_options ${1+"$@"}
+#   eval set dummy "$func_options_result"; shift
+#   ...rest of your script...
+#
+# In order for the '--version' option to work, you will need to have a
+# suitably formatted comment like the one at the top of this file
+# starting with '# Written by ' and ending with '# warranty; '.
+#
+# For '-h' and '--help' to work, you will also need a one line
+# description of your script's purpose in a comment directly above the
+# '# Written by ' line, like the one at the top of this file.
+#
+# The default options also support '--debug', which will turn on shell
+# execution tracing (see the comment above debug_cmd below for another
+# use), and '--verbose' and the func_verbose function to allow your script
+# to display verbose messages only when your user has specified
+# '--verbose'.
+#
+# After sourcing this file, you can plug processing for additional
+# options by amending the variables from the 'Configuration' section
+# below, and following the instructions in the 'Option parsing'
+# section further down.
+
+## -------------- ##
+## Configuration. ##
+## -------------- ##
+
+# You should override these variables in your script after sourcing this
+# file so that they reflect the customisations you have added to the
+# option parser.
+
+# The usage line for option parsing errors and the start of '-h' and
+# '--help' output messages. You can embed shell variables for delayed
+# expansion at the time the message is displayed, but you will need to
+# quote other shell meta-characters carefully to prevent them being
+# expanded when the contents are evaled.
+usage='$progpath [OPTION]...'
+
+# Short help message in response to '-h' and '--help'.  Add to this or
+# override it after sourcing this library to reflect the full set of
+# options your script accepts.
+usage_message="\
+       --debug        enable verbose shell tracing
+   -W, --warnings=CATEGORY
+                      report the warnings falling in CATEGORY [all]
+   -v, --verbose      verbosely report processing
+       --version      print version information and exit
+   -h, --help         print short or long help message and exit
+"
+
+# Additional text appended to 'usage_message' in response to '--help'.
+long_help_message="
+Warning categories include:
+       'all'          show all warnings
+       'none'         turn off all the warnings
+       'error'        warnings are treated as fatal errors"
+
+# Help message printed before fatal option parsing errors.
+fatal_help="Try '\$progname --help' for more information."
+
+
+
+## ------------------------- ##
+## Hook function management. ##
+## ------------------------- ##
+
+# This section contains functions for adding, removing, and running hooks
+# to the main code.  A hook is just a named list of of function, that can
+# be run in order later on.
+
+# func_hookable FUNC_NAME
+# -----------------------
+# Declare that FUNC_NAME will run hooks added with
+# 'func_add_hook FUNC_NAME ...'.
+func_hookable ()
+{
+    $debug_cmd
+
+    func_append hookable_fns " $1"
+}
+
+
+# func_add_hook FUNC_NAME HOOK_FUNC
+# ---------------------------------
+# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must
+# first have been declared "hookable" by a call to 'func_hookable'.
+func_add_hook ()
+{
+    $debug_cmd
+
+    case " $hookable_fns " in
+      *" $1 "*) ;;
+      *) func_fatal_error "'$1' does not accept hook functions." ;;
+    esac
+
+    eval func_append ${1}_hooks '" $2"'
+}
+
+
+# func_remove_hook FUNC_NAME HOOK_FUNC
+# ------------------------------------
+# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.
+func_remove_hook ()
+{
+    $debug_cmd
+
+    eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`'
+}
+
+
+# func_run_hooks FUNC_NAME [ARG]...
+# ---------------------------------
+# Run all hook functions registered to FUNC_NAME.
+# It is assumed that the list of hook functions contains nothing more
+# than a whitespace-delimited list of legal shell function names, and
+# no effort is wasted trying to catch shell meta-characters or preserve
+# whitespace.
+func_run_hooks ()
+{
+    $debug_cmd
+
+    case " $hookable_fns " in
+      *" $1 "*) ;;
+      *) func_fatal_error "'$1' does not support hook funcions.n" ;;
+    esac
+
+    eval _G_hook_fns=\$$1_hooks; shift
+
+    for _G_hook in $_G_hook_fns; do
+      eval $_G_hook '"$@"'
+
+      # store returned options list back into positional
+      # parameters for next 'cmd' execution.
+      eval _G_hook_result=\$${_G_hook}_result
+      eval set dummy "$_G_hook_result"; shift
+    done
+
+    func_quote_for_eval ${1+"$@"}
+    func_run_hooks_result=$func_quote_for_eval_result
+}
+
+
+
+## --------------- ##
+## Option parsing. ##
+## --------------- ##
+
+# In order to add your own option parsing hooks, you must accept the
+# full positional parameter list in your hook function, remove any
+# options that you action, and then pass back the remaining unprocessed
+# options in '<hooked_function_name>_result', escaped suitably for
+# 'eval'.  Like this:
+#
+#    my_options_prep ()
+#    {
+#        $debug_cmd
+#
+#        # Extend the existing usage message.
+#        usage_message=$usage_message'
+#      -s, --silent       don'\''t print informational messages
+#    '
+#
+#        func_quote_for_eval ${1+"$@"}
+#        my_options_prep_result=$func_quote_for_eval_result
+#    }
+#    func_add_hook func_options_prep my_options_prep
+#
+#
+#    my_silent_option ()
+#    {
+#        $debug_cmd
+#
+#        # Note that for efficiency, we parse as many options as we can
+#        # recognise in a loop before passing the remainder back to the
+#        # caller on the first unrecognised argument we encounter.
+#        while test $# -gt 0; do
+#          opt=$1; shift
+#          case $opt in
+#            --silent|-s) opt_silent=: ;;
+#            # Separate non-argument short options:
+#            -s*)         func_split_short_opt "$_G_opt"
+#                         set dummy "$func_split_short_opt_name" \
+#                             "-$func_split_short_opt_arg" ${1+"$@"}
+#                         shift
+#                         ;;
+#            *)            set dummy "$_G_opt" "$*"; shift; break ;;
+#          esac
+#        done
+#
+#        func_quote_for_eval ${1+"$@"}
+#        my_silent_option_result=$func_quote_for_eval_result
+#    }
+#    func_add_hook func_parse_options my_silent_option
+#
+#
+#    my_option_validation ()
+#    {
+#        $debug_cmd
+#
+#        $opt_silent && $opt_verbose && func_fatal_help "\
+#    '--silent' and '--verbose' options are mutually exclusive."
+#
+#        func_quote_for_eval ${1+"$@"}
+#        my_option_validation_result=$func_quote_for_eval_result
+#    }
+#    func_add_hook func_validate_options my_option_validation
+#
+# You'll alse need to manually amend $usage_message to reflect the extra
+# options you parse.  It's preferable to append if you can, so that
+# multiple option parsing hooks can be added safely.
+
+
+# func_options [ARG]...
+# ---------------------
+# All the functions called inside func_options are hookable. See the
+# individual implementations for details.
+func_hookable func_options
+func_options ()
+{
+    $debug_cmd
+
+    func_options_prep ${1+"$@"}
+    eval func_parse_options \
+        ${func_options_prep_result+"$func_options_prep_result"}
+    eval func_validate_options \
+        ${func_parse_options_result+"$func_parse_options_result"}
+
+    eval func_run_hooks func_options \
+        ${func_validate_options_result+"$func_validate_options_result"}
+
+    # save modified positional parameters for caller
+    func_options_result=$func_run_hooks_result
 }
 
 
-# func_quote_for_eval arg
-# Aesthetically quote ARG to be evaled later.
-# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
-# is double-quoted, suitable for a subsequent eval, whereas
-# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
-# which are still active within double quotes backslashified.
-func_quote_for_eval ()
+# func_options_prep [ARG]...
+# --------------------------
+# All initialisations required before starting the option parse loop.
+# Note that when calling hook functions, we pass through the list of
+# positional parameters.  If a hook function modifies that list, and
+# needs to propogate that back to rest of this script, then the complete
+# modified list must be put in 'func_run_hooks_result' before
+# returning.
+func_hookable func_options_prep
+func_options_prep ()
 {
-    case $1 in
-      *[\\\`\"\$]*)
-	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
-      *)
-        func_quote_for_eval_unquoted_result="$1" ;;
-    esac
+    $debug_cmd
 
-    case $func_quote_for_eval_unquoted_result in
-      # Double-quote args containing shell metacharacters to delay
-      # word splitting, command substitution and and variable
-      # expansion for a subsequent eval.
-      # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, so we specify it separately.
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
-        ;;
-      *)
-        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
-    esac
+    # Option defaults:
+    opt_verbose=false
+    opt_warning_types=
+
+    func_run_hooks func_options_prep ${1+"$@"}
+
+    # save modified positional parameters for caller
+    func_options_prep_result=$func_run_hooks_result
 }
 
 
-# func_quote_for_expand arg
-# Aesthetically quote ARG to be evaled later; same as above,
-# but do not quote variable references.
-func_quote_for_expand ()
+# func_parse_options [ARG]...
+# ---------------------------
+# The main option parsing loop.
+func_hookable func_parse_options
+func_parse_options ()
 {
-    case $1 in
-      *[\\\`\"]*)
-	my_arg=`$ECHO "$1" | $SED \
-	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
-      *)
-        my_arg="$1" ;;
-    esac
+    $debug_cmd
 
-    case $my_arg in
-      # Double-quote args containing shell metacharacters to delay
-      # word splitting and command substitution for a subsequent eval.
-      # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, so we specify it separately.
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-        my_arg="\"$my_arg\""
-        ;;
-    esac
+    func_parse_options_result=
 
-    func_quote_for_expand_result="$my_arg"
-}
+    # this just eases exit handling
+    while test $# -gt 0; do
+      # Defer to hook functions for initial option parsing, so they
+      # get priority in the event of reusing an option name.
+      func_run_hooks func_parse_options ${1+"$@"}
 
+      # Adjust func_parse_options positional parameters to match
+      eval set dummy "$func_run_hooks_result"; shift
 
-# func_show_eval cmd [fail_exp]
-# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
-# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
-# is given, then evaluate it.
-func_show_eval ()
-{
-    my_cmd="$1"
-    my_fail_exp="${2-:}"
+      # Break out of the loop if we already parsed every option.
+      test $# -gt 0 || break
 
-    ${opt_silent-false} || {
-      func_quote_for_expand "$my_cmd"
-      eval "func_echo $func_quote_for_expand_result"
-    }
+      _G_opt=$1
+      shift
+      case $_G_opt in
+        --debug|-x)   debug_cmd='set -x'
+                      func_echo "enabling shell trace mode"
+                      $debug_cmd
+                      ;;
+
+        --no-warnings|--no-warning|--no-warn)
+                      set dummy --warnings none ${1+"$@"}
+                      shift
+		      ;;
 
-    if ${opt_dry_run-false}; then :; else
-      eval "$my_cmd"
-      my_status=$?
-      if test "$my_status" -eq 0; then :; else
-	eval "(exit $my_status); $my_fail_exp"
-      fi
-    fi
+        --warnings|--warning|-W)
+                      test $# = 0 && func_missing_arg $_G_opt && break
+                      case " $warning_categories $1" in
+                        *" $1 "*)
+                          # trailing space prevents matching last $1 above
+                          func_append_uniq opt_warning_types " $1"
+                          ;;
+                        *all)
+                          opt_warning_types=$warning_categories
+                          ;;
+                        *none)
+                          opt_warning_types=none
+                          warning_func=:
+                          ;;
+                        *error)
+                          opt_warning_types=$warning_categories
+                          warning_func=func_fatal_error
+                          ;;
+                        *)
+                          func_fatal_error \
+                             "unsupported warning category: '$1'"
+                          ;;
+                      esac
+                      shift
+                      ;;
+
+        --verbose|-v) opt_verbose=: ;;
+        --version)    func_version ;;
+        -\?|-h)       func_usage ;;
+        --help)       func_help ;;
+
+	# Separate optargs to long options (plugins may need this):
+	--*=*)        func_split_equals "$_G_opt"
+	              set dummy "$func_split_equals_lhs" \
+                          "$func_split_equals_rhs" ${1+"$@"}
+                      shift
+                      ;;
+
+       # Separate optargs to short options:
+        -W*)
+                      func_split_short_opt "$_G_opt"
+                      set dummy "$func_split_short_opt_name" \
+                          "$func_split_short_opt_arg" ${1+"$@"}
+                      shift
+                      ;;
+
+        # Separate non-argument short options:
+        -\?*|-h*|-v*|-x*)
+                      func_split_short_opt "$_G_opt"
+                      set dummy "$func_split_short_opt_name" \
+                          "-$func_split_short_opt_arg" ${1+"$@"}
+                      shift
+                      ;;
+
+        --)           break ;;
+        -*)           func_fatal_help "unrecognised option: '$_G_opt'" ;;
+        *)            set dummy "$_G_opt" ${1+"$@"}; shift; break ;;
+      esac
+    done
+
+    # save modified positional parameters for caller
+    func_quote_for_eval ${1+"$@"}
+    func_parse_options_result=$func_quote_for_eval_result
 }
 
 
-# func_show_eval_locale cmd [fail_exp]
-# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
-# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
-# is given, then evaluate it.  Use the saved locale for evaluation.
-func_show_eval_locale ()
+# func_validate_options [ARG]...
+# ------------------------------
+# Perform any sanity checks on option settings and/or unconsumed
+# arguments.
+func_hookable func_validate_options
+func_validate_options ()
 {
-    my_cmd="$1"
-    my_fail_exp="${2-:}"
+    $debug_cmd
 
-    ${opt_silent-false} || {
-      func_quote_for_expand "$my_cmd"
-      eval "func_echo $func_quote_for_expand_result"
-    }
+    # Display all warnings if -W was not given.
+    test -n "$opt_warning_types" || opt_warning_types=" $warning_categories"
 
-    if ${opt_dry_run-false}; then :; else
-      eval "$lt_user_locale
-	    $my_cmd"
-      my_status=$?
-      eval "$lt_safe_locale"
-      if test "$my_status" -eq 0; then :; else
-	eval "(exit $my_status); $my_fail_exp"
-      fi
-    fi
-}
+    func_run_hooks func_validate_options ${1+"$@"}
 
-# func_tr_sh
-# Turn $1 into a string suitable for a shell variable name.
-# Result is stored in $func_tr_sh_result.  All characters
-# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
-# if $1 begins with a digit, a '_' is prepended as well.
-func_tr_sh ()
-{
-  case $1 in
-  [0-9]* | *[!a-zA-Z0-9_]*)
-    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
-    ;;
-  * )
-    func_tr_sh_result=$1
-    ;;
-  esac
+    # Bail if the options were screwed!
+    $exit_cmd $EXIT_FAILURE
+
+    # save modified positional parameters for caller
+    func_validate_options_result=$func_run_hooks_result
 }
 
 
-# func_version
-# Echo version message to standard output and exit.
-func_version ()
-{
-    $opt_debug
 
-    $SED -n '/(C)/!b go
-	:more
-	/\./!{
-	  N
-	  s/\n# / /
-	  b more
-	}
-	:go
-	/^# '$PROGRAM' (GNU /,/# warranty; / {
-        s/^# //
-	s/^# *$//
-        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
-        p
-     }' < "$progpath"
-     exit $?
-}
+## ----------------- ##
+## Helper functions. ##
+## ----------------- ##
 
-# func_usage
-# Echo short help message to standard output and exit.
-func_usage ()
+# This section contains the helper functions used by the rest of the
+# hookable option parser framework in ascii-betical order.
+
+
+# func_fatal_help ARG...
+# ----------------------
+# Echo program name prefixed message to standard error, followed by
+# a help hint, and exit.
+func_fatal_help ()
 {
-    $opt_debug
+    $debug_cmd
 
-    $SED -n '/^# Usage:/,/^#  *.*--help/ {
-        s/^# //
-	s/^# *$//
-	s/\$progname/'$progname'/
-	p
-    }' < "$progpath"
-    echo
-    $ECHO "run \`$progname --help | more' for full usage"
-    exit $?
+    eval \$ECHO \""Usage: $usage"\"
+    eval \$ECHO \""$fatal_help"\"
+    func_error ${1+"$@"}
+    exit $EXIT_FAILURE
 }
 
-# func_help [NOEXIT]
-# Echo long help message to standard output and exit,
-# unless 'noexit' is passed as argument.
+
+# func_help
+# ---------
+# Echo long help message to standard output and exit.
 func_help ()
 {
-    $opt_debug
-
-    $SED -n '/^# Usage:/,/# Report bugs to/ {
-	:print
-        s/^# //
-	s/^# *$//
-	s*\$progname*'$progname'*
-	s*\$host*'"$host"'*
-	s*\$SHELL*'"$SHELL"'*
-	s*\$LTCC*'"$LTCC"'*
-	s*\$LTCFLAGS*'"$LTCFLAGS"'*
-	s*\$LD*'"$LD"'*
-	s/\$with_gnu_ld/'"$with_gnu_ld"'/
-	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
-	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
-	p
-	d
-     }
-     /^# .* home page:/b print
-     /^# General help using/b print
-     ' < "$progpath"
-    ret=$?
-    if test -z "$1"; then
-      exit $ret
-    fi
+    $debug_cmd
+
+    func_usage_message
+    $ECHO "$long_help_message"
+    exit 0
 }
 
-# func_missing_arg argname
+
+# func_missing_arg ARGNAME
+# ------------------------
 # Echo program name prefixed message to standard error and set global
 # exit_cmd.
 func_missing_arg ()
 {
-    $opt_debug
+    $debug_cmd
 
-    func_error "missing argument for $1."
+    func_error "Missing argument for '$1'."
     exit_cmd=exit
 }
 
 
-# func_split_short_opt shortopt
+# func_split_equals STRING
+# ------------------------
+# Set func_split_equals_lhs and func_split_equals_rhs shell variables after
+# splitting STRING at the '=' sign.
+test -z "$_G_HAVE_XSI_OPS" \
+    && (eval 'x=a/b/c;
+      test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \
+    && _G_HAVE_XSI_OPS=yes
+
+if test yes = "$_G_HAVE_XSI_OPS"
+then
+  # This is an XSI compatible shell, allowing a faster implementation...
+  eval 'func_split_equals ()
+  {
+      $debug_cmd
+
+      func_split_equals_lhs=${1%%=*}
+      func_split_equals_rhs=${1#*=}
+      test "x$func_split_equals_lhs" = "x$1" \
+        && func_split_equals_rhs=
+  }'
+else
+  # ...otherwise fall back to using expr, which is often a shell builtin.
+  func_split_equals ()
+  {
+      $debug_cmd
+
+      func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'`
+      func_split_equals_rhs=
+      test "x$func_split_equals_lhs" = "x$1" \
+        || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'`
+  }
+fi #func_split_equals
+
+
+# func_split_short_opt SHORTOPT
+# -----------------------------
 # Set func_split_short_opt_name and func_split_short_opt_arg shell
 # variables after splitting SHORTOPT after the 2nd character.
-func_split_short_opt ()
+if test yes = "$_G_HAVE_XSI_OPS"
+then
+  # This is an XSI compatible shell, allowing a faster implementation...
+  eval 'func_split_short_opt ()
+  {
+      $debug_cmd
+
+      func_split_short_opt_arg=${1#??}
+      func_split_short_opt_name=${1%"$func_split_short_opt_arg"}
+  }'
+else
+  # ...otherwise fall back to using expr, which is often a shell builtin.
+  func_split_short_opt ()
+  {
+      $debug_cmd
+
+      func_split_short_opt_name=`expr "x$1" : 'x-\(.\)'`
+      func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'`
+  }
+fi #func_split_short_opt
+
+
+# func_usage
+# ----------
+# Echo short help message to standard output and exit.
+func_usage ()
 {
-    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
-    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
+    $debug_cmd
 
-    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
-    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
-} # func_split_short_opt may be replaced by extended shell implementation
+    func_usage_message
+    $ECHO "Run '$progname --help |${PAGER-more}' for full usage"
+    exit 0
+}
 
 
-# func_split_long_opt longopt
-# Set func_split_long_opt_name and func_split_long_opt_arg shell
-# variables after splitting LONGOPT at the `=' sign.
-func_split_long_opt ()
+# func_usage_message
+# ------------------
+# Echo short help message to standard output.
+func_usage_message ()
 {
-    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
-    my_sed_long_arg='1s/^--[^=]*=//'
+    $debug_cmd
 
-    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
-    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
-} # func_split_long_opt may be replaced by extended shell implementation
+    eval \$ECHO \""Usage: $usage"\"
+    echo
+    $SED -n 's|^# ||
+        /^Written by/{
+          x;p;x
+        }
+	h
+	/^Written by/q' < "$progpath"
+    echo
+    eval \$ECHO \""$usage_message"\"
+}
 
-exit_cmd=:
 
+# func_version
+# ------------
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $debug_cmd
 
+    printf '%s\n' "$progname $scriptversion"
+    $SED -n '
+        /(C)/!b go
+        :more
+        /\./!{
+          N
+          s|\n# | |
+          b more
+        }
+        :go
+        /^# Written by /,/# warranty; / {
+          s|^# ||
+          s|^# *$||
+          s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2|
+          p
+        }
+        /^# Written by / {
+          s|^# ||
+          p
+        }
+        /^warranty; /q' < "$progpath"
 
+    exit $?
+}
 
 
-magic="%%%MAGIC variable%%%"
-magic_exe="%%%MAGIC EXE variable%%%"
+# Local variables:
+# mode: shell-script
+# sh-indentation: 2
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-pattern: "10/scriptversion=%:y-%02m-%02d.%02H; # UTC"
+# time-stamp-time-zone: "UTC"
+# End:
 
-# Global variables.
-nonopt=
-preserve_args=
-lo2o="s/\\.lo\$/.${objext}/"
-o2lo="s/\\.${objext}\$/.lo/"
-extracted_archives=
-extracted_serial=0
+# Set a version string.
+scriptversion='(GNU libtool) 2.4.6'
 
-# If this variable is set in any of the actions, the command in it
-# will be execed at the end.  This prevents here-documents from being
-# left over by shells.
-exec_cmd=
 
-# func_append var value
-# Append VALUE to the end of shell variable VAR.
-func_append ()
+# func_echo ARG...
+# ----------------
+# Libtool also displays the current mode in messages, so override
+# funclib.sh func_echo with this custom definition.
+func_echo ()
 {
-    eval "${1}=\$${1}\${2}"
-} # func_append may be replaced by extended shell implementation
+    $debug_cmd
 
-# func_append_quoted var value
-# Quote VALUE and append to the end of shell variable VAR, separated
-# by a space.
-func_append_quoted ()
-{
-    func_quote_for_eval "${2}"
-    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
-} # func_append_quoted may be replaced by extended shell implementation
+    _G_message=$*
 
+    func_echo_IFS=$IFS
+    IFS=$nl
+    for _G_line in $_G_message; do
+      IFS=$func_echo_IFS
+      $ECHO "$progname${opt_mode+: $opt_mode}: $_G_line"
+    done
+    IFS=$func_echo_IFS
+}
 
-# func_arith arithmetic-term...
-func_arith ()
+
+# func_warning ARG...
+# -------------------
+# Libtool warnings are not categorized, so override funclib.sh
+# func_warning with this simpler definition.
+func_warning ()
 {
-    func_arith_result=`expr "${@}"`
-} # func_arith may be replaced by extended shell implementation
+    $debug_cmd
 
+    $warning_func ${1+"$@"}
+}
 
-# func_len string
-# STRING may not start with a hyphen.
-func_len ()
-{
-    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
-} # func_len may be replaced by extended shell implementation
 
+## ---------------- ##
+## Options parsing. ##
+## ---------------- ##
+
+# Hook in the functions to make sure our own options are parsed during
+# the option parsing loop.
+
+usage='$progpath [OPTION]... [MODE-ARG]...'
+
+# Short help message in response to '-h'.
+usage_message="Options:
+       --config             show all configuration variables
+       --debug              enable verbose shell tracing
+   -n, --dry-run            display commands without modifying any files
+       --features           display basic configuration information and exit
+       --mode=MODE          use operation mode MODE
+       --no-warnings        equivalent to '-Wnone'
+       --preserve-dup-deps  don't remove duplicate dependency libraries
+       --quiet, --silent    don't print informational messages
+       --tag=TAG            use configuration variables from tag TAG
+   -v, --verbose            print more informational messages than default
+       --version            print version information
+   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]
+   -h, --help, --help-all   print short, long, or detailed help message
+"
 
-# func_lo2o object
-func_lo2o ()
+# Additional text appended to 'usage_message' in response to '--help'.
+func_help ()
 {
-    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
-} # func_lo2o may be replaced by extended shell implementation
+    $debug_cmd
+
+    func_usage_message
+    $ECHO "$long_help_message
+
+MODE must be one of the following:
+
+       clean           remove files from the build directory
+       compile         compile a source file into a libtool object
+       execute         automatically set library path, then run a program
+       finish          complete the installation of libtool libraries
+       install         install libraries or executables
+       link            create a library or an executable
+       uninstall       remove libraries from an installed directory
+
+MODE-ARGS vary depending on the MODE.  When passed as first option,
+'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.
+Try '$progname --help --mode=MODE' for a more detailed description of MODE.
+
+When reporting a bug, please describe a test case to reproduce it and
+include the following information:
+
+       host-triplet:   $host
+       shell:          $SHELL
+       compiler:       $LTCC
+       compiler flags: $LTCFLAGS
+       linker:         $LD (gnu? $with_gnu_ld)
+       version:        $progname $scriptversion Debian-2.4.6-2
+       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`
+       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`
+
+Report bugs to <bug-libtool at gnu.org>.
+GNU libtool home page: <http://www.gnu.org/s/libtool/>.
+General help using GNU software: <http://www.gnu.org/gethelp/>."
+    exit 0
+}
 
 
-# func_xform libobj-or-source
-func_xform ()
-{
-    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
-} # func_xform may be replaced by extended shell implementation
+# func_lo2o OBJECT-NAME
+# ---------------------
+# Transform OBJECT-NAME from a '.lo' suffix to the platform specific
+# object suffix.
+
+lo2o=s/\\.lo\$/.$objext/
+o2lo=s/\\.$objext\$/.lo/
+
+if test yes = "$_G_HAVE_XSI_OPS"; then
+  eval 'func_lo2o ()
+  {
+    case $1 in
+      *.lo) func_lo2o_result=${1%.lo}.$objext ;;
+      *   ) func_lo2o_result=$1               ;;
+    esac
+  }'
+
+  # func_xform LIBOBJ-OR-SOURCE
+  # ---------------------------
+  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)
+  # suffix to a '.lo' libtool-object suffix.
+  eval 'func_xform ()
+  {
+    func_xform_result=${1%.*}.lo
+  }'
+else
+  # ...otherwise fall back to using sed.
+  func_lo2o ()
+  {
+    func_lo2o_result=`$ECHO "$1" | $SED "$lo2o"`
+  }
+
+  func_xform ()
+  {
+    func_xform_result=`$ECHO "$1" | $SED 's|\.[^.]*$|.lo|'`
+  }
+fi
 
 
-# func_fatal_configuration arg...
+# func_fatal_configuration ARG...
+# -------------------------------
 # Echo program name prefixed message to standard error, followed by
 # a configuration failure hint, and exit.
 func_fatal_configuration ()
 {
-    func_error ${1+"$@"}
-    func_error "See the $PACKAGE documentation for more information."
-    func_fatal_error "Fatal configuration error."
+    func__fatal_error ${1+"$@"} \
+      "See the $PACKAGE documentation for more information." \
+      "Fatal configuration error."
 }
 
 
 # func_config
+# -----------
 # Display the configuration for all the tags in this script.
 func_config ()
 {
@@ -915,17 +2149,19 @@ func_config ()
     exit $?
 }
 
+
 # func_features
+# -------------
 # Display the features supported by this script.
 func_features ()
 {
     echo "host: $host"
-    if test "$build_libtool_libs" = yes; then
+    if test yes = "$build_libtool_libs"; then
       echo "enable shared libraries"
     else
       echo "disable shared libraries"
     fi
-    if test "$build_old_libs" = yes; then
+    if test yes = "$build_old_libs"; then
       echo "enable static libraries"
     else
       echo "disable static libraries"
@@ -934,314 +2170,350 @@ func_features ()
     exit $?
 }
 
-# func_enable_tag tagname
+
+# func_enable_tag TAGNAME
+# -----------------------
 # Verify that TAGNAME is valid, and either flag an error and exit, or
 # enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
 # variable here.
 func_enable_tag ()
 {
-  # Global variable:
-  tagname="$1"
+    # Global variable:
+    tagname=$1
 
-  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
-  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
-  sed_extractcf="/$re_begincf/,/$re_endcf/p"
+    re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
+    re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
+    sed_extractcf=/$re_begincf/,/$re_endcf/p
 
-  # Validate tagname.
-  case $tagname in
-    *[!-_A-Za-z0-9,/]*)
-      func_fatal_error "invalid tag name: $tagname"
-      ;;
-  esac
+    # Validate tagname.
+    case $tagname in
+      *[!-_A-Za-z0-9,/]*)
+        func_fatal_error "invalid tag name: $tagname"
+        ;;
+    esac
 
-  # Don't test for the "default" C tag, as we know it's
-  # there but not specially marked.
-  case $tagname in
-    CC) ;;
+    # Don't test for the "default" C tag, as we know it's
+    # there but not specially marked.
+    case $tagname in
+        CC) ;;
     *)
-      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
-	taglist="$taglist $tagname"
-
-	# Evaluate the configuration.  Be careful to quote the path
-	# and the sed script, to avoid splitting on whitespace, but
-	# also don't use non-portable quotes within backquotes within
-	# quotes we have to do it in 2 steps:
-	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
-	eval "$extractedcf"
-      else
-	func_error "ignoring unknown tag $tagname"
-      fi
-      ;;
-  esac
+        if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
+	  taglist="$taglist $tagname"
+
+	  # Evaluate the configuration.  Be careful to quote the path
+	  # and the sed script, to avoid splitting on whitespace, but
+	  # also don't use non-portable quotes within backquotes within
+	  # quotes we have to do it in 2 steps:
+	  extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
+	  eval "$extractedcf"
+        else
+	  func_error "ignoring unknown tag $tagname"
+        fi
+        ;;
+    esac
 }
 
+
 # func_check_version_match
+# ------------------------
 # Ensure that we are using m4 macros, and libtool script from the same
 # release of libtool.
 func_check_version_match ()
 {
-  if test "$package_revision" != "$macro_revision"; then
-    if test "$VERSION" != "$macro_version"; then
-      if test -z "$macro_version"; then
-        cat >&2 <<_LT_EOF
+    if test "$package_revision" != "$macro_revision"; then
+      if test "$VERSION" != "$macro_version"; then
+        if test -z "$macro_version"; then
+          cat >&2 <<_LT_EOF
 $progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
 $progname: definition of this LT_INIT comes from an older release.
 $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
 $progname: and run autoconf again.
 _LT_EOF
-      else
-        cat >&2 <<_LT_EOF
+        else
+          cat >&2 <<_LT_EOF
 $progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
 $progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
 $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
 $progname: and run autoconf again.
 _LT_EOF
-      fi
-    else
-      cat >&2 <<_LT_EOF
+        fi
+      else
+        cat >&2 <<_LT_EOF
 $progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
 $progname: but the definition of this LT_INIT comes from revision $macro_revision.
 $progname: You should recreate aclocal.m4 with macros from revision $package_revision
 $progname: of $PACKAGE $VERSION and run autoconf again.
 _LT_EOF
-    fi
+      fi
 
-    exit $EXIT_MISMATCH
-  fi
+      exit $EXIT_MISMATCH
+    fi
 }
 
 
-# Shorthand for --mode=foo, only valid as the first argument
-case $1 in
-clean|clea|cle|cl)
-  shift; set dummy --mode clean ${1+"$@"}; shift
-  ;;
-compile|compil|compi|comp|com|co|c)
-  shift; set dummy --mode compile ${1+"$@"}; shift
-  ;;
-execute|execut|execu|exec|exe|ex|e)
-  shift; set dummy --mode execute ${1+"$@"}; shift
-  ;;
-finish|finis|fini|fin|fi|f)
-  shift; set dummy --mode finish ${1+"$@"}; shift
-  ;;
-install|instal|insta|inst|ins|in|i)
-  shift; set dummy --mode install ${1+"$@"}; shift
-  ;;
-link|lin|li|l)
-  shift; set dummy --mode link ${1+"$@"}; shift
-  ;;
-uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
-  shift; set dummy --mode uninstall ${1+"$@"}; shift
-  ;;
-esac
+# libtool_options_prep [ARG]...
+# -----------------------------
+# Preparation for options parsed by libtool.
+libtool_options_prep ()
+{
+    $debug_mode
 
+    # Option defaults:
+    opt_config=false
+    opt_dlopen=
+    opt_dry_run=false
+    opt_help=false
+    opt_mode=
+    opt_preserve_dup_deps=false
+    opt_quiet=false
 
+    nonopt=
+    preserve_args=
 
-# Option defaults:
-opt_debug=:
-opt_dry_run=false
-opt_config=false
-opt_preserve_dup_deps=false
-opt_features=false
-opt_finish=false
-opt_help=false
-opt_help_all=false
-opt_silent=:
-opt_warning=:
-opt_verbose=:
-opt_silent=false
-opt_verbose=false
+    # Shorthand for --mode=foo, only valid as the first argument
+    case $1 in
+    clean|clea|cle|cl)
+      shift; set dummy --mode clean ${1+"$@"}; shift
+      ;;
+    compile|compil|compi|comp|com|co|c)
+      shift; set dummy --mode compile ${1+"$@"}; shift
+      ;;
+    execute|execut|execu|exec|exe|ex|e)
+      shift; set dummy --mode execute ${1+"$@"}; shift
+      ;;
+    finish|finis|fini|fin|fi|f)
+      shift; set dummy --mode finish ${1+"$@"}; shift
+      ;;
+    install|instal|insta|inst|ins|in|i)
+      shift; set dummy --mode install ${1+"$@"}; shift
+      ;;
+    link|lin|li|l)
+      shift; set dummy --mode link ${1+"$@"}; shift
+      ;;
+    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+      shift; set dummy --mode uninstall ${1+"$@"}; shift
+      ;;
+    esac
+
+    # Pass back the list of options.
+    func_quote_for_eval ${1+"$@"}
+    libtool_options_prep_result=$func_quote_for_eval_result
+}
+func_add_hook func_options_prep libtool_options_prep
 
 
-# Parse options once, thoroughly.  This comes as soon as possible in the
-# script to make things like `--version' happen as quickly as we can.
+# libtool_parse_options [ARG]...
+# ---------------------------------
+# Provide handling for libtool specific options.
+libtool_parse_options ()
 {
-  # this just eases exit handling
-  while test $# -gt 0; do
-    opt="$1"
-    shift
-    case $opt in
-      --debug|-x)	opt_debug='set -x'
-			func_echo "enabling shell trace mode"
-			$opt_debug
-			;;
-      --dry-run|--dryrun|-n)
-			opt_dry_run=:
-			;;
-      --config)
-			opt_config=:
-func_config
-			;;
-      --dlopen|-dlopen)
-			optarg="$1"
-			opt_dlopen="${opt_dlopen+$opt_dlopen
-}$optarg"
-			shift
-			;;
-      --preserve-dup-deps)
-			opt_preserve_dup_deps=:
-			;;
-      --features)
-			opt_features=:
-func_features
-			;;
-      --finish)
-			opt_finish=:
-set dummy --mode finish ${1+"$@"}; shift
-			;;
-      --help)
-			opt_help=:
-			;;
-      --help-all)
-			opt_help_all=:
-opt_help=': help-all'
-			;;
-      --mode)
-			test $# = 0 && func_missing_arg $opt && break
-			optarg="$1"
-			opt_mode="$optarg"
-case $optarg in
-  # Valid mode arguments:
-  clean|compile|execute|finish|install|link|relink|uninstall) ;;
-
-  # Catch anything else as an error
-  *) func_error "invalid argument for $opt"
-     exit_cmd=exit
-     break
-     ;;
-esac
-			shift
-			;;
-      --no-silent|--no-quiet)
-			opt_silent=false
-func_append preserve_args " $opt"
-			;;
-      --no-warning|--no-warn)
-			opt_warning=false
-func_append preserve_args " $opt"
-			;;
-      --no-verbose)
-			opt_verbose=false
-func_append preserve_args " $opt"
-			;;
-      --silent|--quiet)
-			opt_silent=:
-func_append preserve_args " $opt"
-        opt_verbose=false
-			;;
-      --verbose|-v)
-			opt_verbose=:
-func_append preserve_args " $opt"
-opt_silent=false
-			;;
-      --tag)
-			test $# = 0 && func_missing_arg $opt && break
-			optarg="$1"
-			opt_tag="$optarg"
-func_append preserve_args " $opt $optarg"
-func_enable_tag "$optarg"
-			shift
-			;;
-
-      -\?|-h)		func_usage				;;
-      --help)		func_help				;;
-      --version)	func_version				;;
-
-      # Separate optargs to long options:
-      --*=*)
-			func_split_long_opt "$opt"
-			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
-			shift
-			;;
-
-      # Separate non-argument short options:
-      -\?*|-h*|-n*|-v*)
-			func_split_short_opt "$opt"
-			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
-			shift
-			;;
-
-      --)		break					;;
-      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
-      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
-    esac
-  done
+    $debug_cmd
 
-  # Validate options:
+    # Perform our own loop to consume as many options as possible in
+    # each iteration.
+    while test $# -gt 0; do
+      _G_opt=$1
+      shift
+      case $_G_opt in
+        --dry-run|--dryrun|-n)
+                        opt_dry_run=:
+                        ;;
+
+        --config)       func_config ;;
+
+        --dlopen|-dlopen)
+                        opt_dlopen="${opt_dlopen+$opt_dlopen
+}$1"
+                        shift
+                        ;;
+
+        --preserve-dup-deps)
+                        opt_preserve_dup_deps=: ;;
+
+        --features)     func_features ;;
+
+        --finish)       set dummy --mode finish ${1+"$@"}; shift ;;
+
+        --help)         opt_help=: ;;
+
+        --help-all)     opt_help=': help-all' ;;
+
+        --mode)         test $# = 0 && func_missing_arg $_G_opt && break
+                        opt_mode=$1
+                        case $1 in
+                          # Valid mode arguments:
+                          clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+                          # Catch anything else as an error
+                          *) func_error "invalid argument for $_G_opt"
+                             exit_cmd=exit
+                             break
+                             ;;
+                        esac
+                        shift
+                        ;;
+
+        --no-silent|--no-quiet)
+                        opt_quiet=false
+                        func_append preserve_args " $_G_opt"
+                        ;;
+
+        --no-warnings|--no-warning|--no-warn)
+                        opt_warning=false
+                        func_append preserve_args " $_G_opt"
+                        ;;
+
+        --no-verbose)
+                        opt_verbose=false
+                        func_append preserve_args " $_G_opt"
+                        ;;
+
+        --silent|--quiet)
+                        opt_quiet=:
+                        opt_verbose=false
+                        func_append preserve_args " $_G_opt"
+                        ;;
+
+        --tag)          test $# = 0 && func_missing_arg $_G_opt && break
+                        opt_tag=$1
+                        func_append preserve_args " $_G_opt $1"
+                        func_enable_tag "$1"
+                        shift
+                        ;;
+
+        --verbose|-v)   opt_quiet=false
+                        opt_verbose=:
+                        func_append preserve_args " $_G_opt"
+                        ;;
+
+	# An option not handled by this hook function:
+        *)		set dummy "$_G_opt" ${1+"$@"};	shift; break  ;;
+      esac
+    done
 
-  # save first non-option argument
-  if test "$#" -gt 0; then
-    nonopt="$opt"
-    shift
-  fi
 
-  # preserve --debug
-  test "$opt_debug" = : || func_append preserve_args " --debug"
+    # save modified positional parameters for caller
+    func_quote_for_eval ${1+"$@"}
+    libtool_parse_options_result=$func_quote_for_eval_result
+}
+func_add_hook func_parse_options libtool_parse_options
 
-  case $host in
-    *cygwin* | *mingw* | *pw32* | *cegcc*)
-      # don't eliminate duplications in $postdeps and $predeps
-      opt_duplicate_compiler_generated_deps=:
-      ;;
-    *)
-      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
-      ;;
-  esac
 
-  $opt_help || {
-    # Sanity checks first:
-    func_check_version_match
 
-    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
-      func_fatal_configuration "not configured to build any kind of library"
+# libtool_validate_options [ARG]...
+# ---------------------------------
+# Perform any sanity checks on option settings and/or unconsumed
+# arguments.
+libtool_validate_options ()
+{
+    # save first non-option argument
+    if test 0 -lt $#; then
+      nonopt=$1
+      shift
     fi
 
-    # Darwin sucks
-    eval std_shrext=\"$shrext_cmds\"
+    # preserve --debug
+    test : = "$debug_cmd" || func_append preserve_args " --debug"
 
-    # Only execute mode is allowed to have -dlopen flags.
-    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
-      func_error "unrecognized option \`-dlopen'"
-      $ECHO "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
+    case $host in
+      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452
+      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788
+      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)
+        # don't eliminate duplications in $postdeps and $predeps
+        opt_duplicate_compiler_generated_deps=:
+        ;;
+      *)
+        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
+        ;;
+    esac
 
-    # Change the help message to a mode-specific one.
-    generic_help="$help"
-    help="Try \`$progname --help --mode=$opt_mode' for more information."
-  }
+    $opt_help || {
+      # Sanity checks first:
+      func_check_version_match
+
+      test yes != "$build_libtool_libs" \
+        && test yes != "$build_old_libs" \
+        && func_fatal_configuration "not configured to build any kind of library"
+
+      # Darwin sucks
+      eval std_shrext=\"$shrext_cmds\"
+
+      # Only execute mode is allowed to have -dlopen flags.
+      if test -n "$opt_dlopen" && test execute != "$opt_mode"; then
+        func_error "unrecognized option '-dlopen'"
+        $ECHO "$help" 1>&2
+        exit $EXIT_FAILURE
+      fi
 
+      # Change the help message to a mode-specific one.
+      generic_help=$help
+      help="Try '$progname --help --mode=$opt_mode' for more information."
+    }
 
-  # Bail if the options were screwed
-  $exit_cmd $EXIT_FAILURE
+    # Pass back the unparsed argument list
+    func_quote_for_eval ${1+"$@"}
+    libtool_validate_options_result=$func_quote_for_eval_result
 }
+func_add_hook func_validate_options libtool_validate_options
 
 
+# Process options as early as possible so that --help and --version
+# can return quickly.
+func_options ${1+"$@"}
+eval set dummy "$func_options_result"; shift
+
 
 
 ## ----------- ##
 ##    Main.    ##
 ## ----------- ##
 
+magic='%%%MAGIC variable%%%'
+magic_exe='%%%MAGIC EXE variable%%%'
+
+# Global variables.
+extracted_archives=
+extracted_serial=0
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=
+
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
+# func_generated_by_libtool
+# True iff stdin has been generated by Libtool. This function is only
+# a basic sanity check; it will hardly flush out determined imposters.
+func_generated_by_libtool_p ()
+{
+  $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+}
+
 # func_lalib_p file
-# True iff FILE is a libtool `.la' library or `.lo' object file.
+# True iff FILE is a libtool '.la' library or '.lo' object file.
 # This function is only a basic sanity check; it will hardly flush out
 # determined imposters.
 func_lalib_p ()
 {
     test -f "$1" &&
-      $SED -e 4q "$1" 2>/dev/null \
-        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+      $SED -e 4q "$1" 2>/dev/null | func_generated_by_libtool_p
 }
 
 # func_lalib_unsafe_p file
-# True iff FILE is a libtool `.la' library or `.lo' object file.
+# True iff FILE is a libtool '.la' library or '.lo' object file.
 # This function implements the same check as func_lalib_p without
 # resorting to external programs.  To this end, it redirects stdin and
 # closes it afterwards, without saving the original file descriptor.
 # As a safety measure, use it only where a negative result would be
-# fatal anyway.  Works if `file' does not exist.
+# fatal anyway.  Works if 'file' does not exist.
 func_lalib_unsafe_p ()
 {
     lalib_p=no
@@ -1249,13 +2521,13 @@ func_lalib_unsafe_p ()
 	for lalib_p_l in 1 2 3 4
 	do
 	    read lalib_p_line
-	    case "$lalib_p_line" in
+	    case $lalib_p_line in
 		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
 	    esac
 	done
 	exec 0<&5 5<&-
     fi
-    test "$lalib_p" = yes
+    test yes = "$lalib_p"
 }
 
 # func_ltwrapper_script_p file
@@ -1264,7 +2536,8 @@ func_lalib_unsafe_p ()
 # determined imposters.
 func_ltwrapper_script_p ()
 {
-    func_lalib_p "$1"
+    test -f "$1" &&
+      $lt_truncate_bin < "$1" 2>/dev/null | func_generated_by_libtool_p
 }
 
 # func_ltwrapper_executable_p file
@@ -1289,7 +2562,7 @@ func_ltwrapper_scriptname ()
 {
     func_dirname_and_basename "$1" "" "."
     func_stripname '' '.exe' "$func_basename_result"
-    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
+    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper
 }
 
 # func_ltwrapper_p file
@@ -1308,11 +2581,13 @@ func_ltwrapper_p ()
 # FAIL_CMD may read-access the current command in variable CMD!
 func_execute_cmds ()
 {
-    $opt_debug
+    $debug_cmd
+
     save_ifs=$IFS; IFS='~'
     for cmd in $1; do
-      IFS=$save_ifs
+      IFS=$sp$nl
       eval cmd=\"$cmd\"
+      IFS=$save_ifs
       func_show_eval "$cmd" "${2-:}"
     done
     IFS=$save_ifs
@@ -1324,10 +2599,11 @@ func_execute_cmds ()
 # Note that it is not necessary on cygwin/mingw to append a dot to
 # FILE even if both FILE and FILE.exe exist: automatic-append-.exe
 # behavior happens only for exec(3), not for open(2)!  Also, sourcing
-# `FILE.' does not work on cygwin managed mounts.
+# 'FILE.' does not work on cygwin managed mounts.
 func_source ()
 {
-    $opt_debug
+    $debug_cmd
+
     case $1 in
     */* | *\\*)	. "$1" ;;
     *)		. "./$1" ;;
@@ -1354,10 +2630,10 @@ func_resolve_sysroot ()
 # store the result into func_replace_sysroot_result.
 func_replace_sysroot ()
 {
-  case "$lt_sysroot:$1" in
+  case $lt_sysroot:$1 in
   ?*:"$lt_sysroot"*)
     func_stripname "$lt_sysroot" '' "$1"
-    func_replace_sysroot_result="=$func_stripname_result"
+    func_replace_sysroot_result='='$func_stripname_result
     ;;
   *)
     # Including no sysroot.
@@ -1374,7 +2650,8 @@ func_replace_sysroot ()
 # arg is usually of the form 'gcc ...'
 func_infer_tag ()
 {
-    $opt_debug
+    $debug_cmd
+
     if test -n "$available_tags" && test -z "$tagname"; then
       CC_quoted=
       for arg in $CC; do
@@ -1393,7 +2670,7 @@ func_infer_tag ()
 	for z in $available_tags; do
 	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
 	    # Evaluate the configuration.
-	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+	    eval "`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
 	    CC_quoted=
 	    for arg in $CC; do
 	      # Double-quote args containing other shell metacharacters.
@@ -1418,7 +2695,7 @@ func_infer_tag ()
 	# line option must be used.
 	if test -z "$tagname"; then
 	  func_echo "unable to infer tagged configuration"
-	  func_fatal_error "specify a tag with \`--tag'"
+	  func_fatal_error "specify a tag with '--tag'"
 #	else
 #	  func_verbose "using $tagname tagged configuration"
 	fi
@@ -1434,15 +2711,15 @@ func_infer_tag ()
 # but don't create it if we're doing a dry run.
 func_write_libtool_object ()
 {
-    write_libobj=${1}
-    if test "$build_libtool_libs" = yes; then
-      write_lobj=\'${2}\'
+    write_libobj=$1
+    if test yes = "$build_libtool_libs"; then
+      write_lobj=\'$2\'
     else
       write_lobj=none
     fi
 
-    if test "$build_old_libs" = yes; then
-      write_oldobj=\'${3}\'
+    if test yes = "$build_old_libs"; then
+      write_oldobj=\'$3\'
     else
       write_oldobj=none
     fi
@@ -1450,7 +2727,7 @@ func_write_libtool_object ()
     $opt_dry_run || {
       cat >${write_libobj}T <<EOF
 # $write_libobj - a libtool object file
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+# Generated by $PROGRAM (GNU $PACKAGE) $VERSION
 #
 # Please DO NOT delete this file!
 # It is necessary for linking the library.
@@ -1462,7 +2739,7 @@ pic_object=$write_lobj
 non_pic_object=$write_oldobj
 
 EOF
-      $MV "${write_libobj}T" "${write_libobj}"
+      $MV "${write_libobj}T" "$write_libobj"
     }
 }
 
@@ -1482,8 +2759,9 @@ EOF
 # be empty on error (or when ARG is empty)
 func_convert_core_file_wine_to_w32 ()
 {
-  $opt_debug
-  func_convert_core_file_wine_to_w32_result="$1"
+  $debug_cmd
+
+  func_convert_core_file_wine_to_w32_result=$1
   if test -n "$1"; then
     # Unfortunately, winepath does not exit with a non-zero error code, so we
     # are forced to check the contents of stdout. On the other hand, if the
@@ -1491,9 +2769,9 @@ func_convert_core_file_wine_to_w32 ()
     # *an error message* to stdout. So we must check for both error code of
     # zero AND non-empty stdout, which explains the odd construction:
     func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
-    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
+    if test "$?" -eq 0 && test -n "$func_convert_core_file_wine_to_w32_tmp"; then
       func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
-        $SED -e "$lt_sed_naive_backslashify"`
+        $SED -e "$sed_naive_backslashify"`
     else
       func_convert_core_file_wine_to_w32_result=
     fi
@@ -1514,18 +2792,19 @@ func_convert_core_file_wine_to_w32 ()
 # are convertible, then the result may be empty.
 func_convert_core_path_wine_to_w32 ()
 {
-  $opt_debug
+  $debug_cmd
+
   # unfortunately, winepath doesn't convert paths, only file names
-  func_convert_core_path_wine_to_w32_result=""
+  func_convert_core_path_wine_to_w32_result=
   if test -n "$1"; then
     oldIFS=$IFS
     IFS=:
     for func_convert_core_path_wine_to_w32_f in $1; do
       IFS=$oldIFS
       func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
-      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+      if test -n "$func_convert_core_file_wine_to_w32_result"; then
         if test -z "$func_convert_core_path_wine_to_w32_result"; then
-          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
+          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result
         else
           func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
         fi
@@ -1554,7 +2833,8 @@ func_convert_core_path_wine_to_w32 ()
 # environment variable; do not put it in $PATH.
 func_cygpath ()
 {
-  $opt_debug
+  $debug_cmd
+
   if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
     func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
     if test "$?" -ne 0; then
@@ -1563,7 +2843,7 @@ func_cygpath ()
     fi
   else
     func_cygpath_result=
-    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
+    func_error "LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'"
   fi
 }
 #end: func_cygpath
@@ -1574,10 +2854,11 @@ func_cygpath ()
 # result in func_convert_core_msys_to_w32_result.
 func_convert_core_msys_to_w32 ()
 {
-  $opt_debug
+  $debug_cmd
+
   # awkward: cmd appends spaces to result
   func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
-    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+    $SED -e 's/[ ]*$//' -e "$sed_naive_backslashify"`
 }
 #end: func_convert_core_msys_to_w32
 
@@ -1588,13 +2869,14 @@ func_convert_core_msys_to_w32 ()
 # func_to_host_file_result to ARG1).
 func_convert_file_check ()
 {
-  $opt_debug
-  if test -z "$2" && test -n "$1" ; then
+  $debug_cmd
+
+  if test -z "$2" && test -n "$1"; then
     func_error "Could not determine host file name corresponding to"
-    func_error "  \`$1'"
+    func_error "  '$1'"
     func_error "Continuing, but uninstalled executables may not work."
     # Fallback:
-    func_to_host_file_result="$1"
+    func_to_host_file_result=$1
   fi
 }
 # end func_convert_file_check
@@ -1606,10 +2888,11 @@ func_convert_file_check ()
 # func_to_host_file_result to a simplistic fallback value (see below).
 func_convert_path_check ()
 {
-  $opt_debug
+  $debug_cmd
+
   if test -z "$4" && test -n "$3"; then
     func_error "Could not determine the host path corresponding to"
-    func_error "  \`$3'"
+    func_error "  '$3'"
     func_error "Continuing, but uninstalled executables may not work."
     # Fallback.  This is a deliberately simplistic "conversion" and
     # should not be "improved".  See libtool.info.
@@ -1618,7 +2901,7 @@ func_convert_path_check ()
       func_to_host_path_result=`echo "$3" |
         $SED -e "$lt_replace_pathsep_chars"`
     else
-      func_to_host_path_result="$3"
+      func_to_host_path_result=$3
     fi
   fi
 }
@@ -1630,9 +2913,10 @@ func_convert_path_check ()
 # and appending REPL if ORIG matches BACKPAT.
 func_convert_path_front_back_pathsep ()
 {
-  $opt_debug
+  $debug_cmd
+
   case $4 in
-  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
+  $1 ) func_to_host_path_result=$3$func_to_host_path_result
     ;;
   esac
   case $4 in
@@ -1646,7 +2930,7 @@ func_convert_path_front_back_pathsep ()
 ##################################################
 # $build to $host FILE NAME CONVERSION FUNCTIONS #
 ##################################################
-# invoked via `$to_host_file_cmd ARG'
+# invoked via '$to_host_file_cmd ARG'
 #
 # In each case, ARG is the path to be converted from $build to $host format.
 # Result will be available in $func_to_host_file_result.
@@ -1657,7 +2941,8 @@ func_convert_path_front_back_pathsep ()
 # in func_to_host_file_result.
 func_to_host_file ()
 {
-  $opt_debug
+  $debug_cmd
+
   $to_host_file_cmd "$1"
 }
 # end func_to_host_file
@@ -1669,7 +2954,8 @@ func_to_host_file ()
 # in (the comma separated) LAZY, no conversion takes place.
 func_to_tool_file ()
 {
-  $opt_debug
+  $debug_cmd
+
   case ,$2, in
     *,"$to_tool_file_cmd",*)
       func_to_tool_file_result=$1
@@ -1687,7 +2973,7 @@ func_to_tool_file ()
 # Copy ARG to func_to_host_file_result.
 func_convert_file_noop ()
 {
-  func_to_host_file_result="$1"
+  func_to_host_file_result=$1
 }
 # end func_convert_file_noop
 
@@ -1698,11 +2984,12 @@ func_convert_file_noop ()
 # func_to_host_file_result.
 func_convert_file_msys_to_w32 ()
 {
-  $opt_debug
-  func_to_host_file_result="$1"
+  $debug_cmd
+
+  func_to_host_file_result=$1
   if test -n "$1"; then
     func_convert_core_msys_to_w32 "$1"
-    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result=$func_convert_core_msys_to_w32_result
   fi
   func_convert_file_check "$1" "$func_to_host_file_result"
 }
@@ -1714,8 +3001,9 @@ func_convert_file_msys_to_w32 ()
 # func_to_host_file_result.
 func_convert_file_cygwin_to_w32 ()
 {
-  $opt_debug
-  func_to_host_file_result="$1"
+  $debug_cmd
+
+  func_to_host_file_result=$1
   if test -n "$1"; then
     # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
     # LT_CYGPATH in this case.
@@ -1731,11 +3019,12 @@ func_convert_file_cygwin_to_w32 ()
 # and a working winepath. Returns result in func_to_host_file_result.
 func_convert_file_nix_to_w32 ()
 {
-  $opt_debug
-  func_to_host_file_result="$1"
+  $debug_cmd
+
+  func_to_host_file_result=$1
   if test -n "$1"; then
     func_convert_core_file_wine_to_w32 "$1"
-    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result
   fi
   func_convert_file_check "$1" "$func_to_host_file_result"
 }
@@ -1747,12 +3036,13 @@ func_convert_file_nix_to_w32 ()
 # Returns result in func_to_host_file_result.
 func_convert_file_msys_to_cygwin ()
 {
-  $opt_debug
-  func_to_host_file_result="$1"
+  $debug_cmd
+
+  func_to_host_file_result=$1
   if test -n "$1"; then
     func_convert_core_msys_to_w32 "$1"
     func_cygpath -u "$func_convert_core_msys_to_w32_result"
-    func_to_host_file_result="$func_cygpath_result"
+    func_to_host_file_result=$func_cygpath_result
   fi
   func_convert_file_check "$1" "$func_to_host_file_result"
 }
@@ -1765,13 +3055,14 @@ func_convert_file_msys_to_cygwin ()
 # in func_to_host_file_result.
 func_convert_file_nix_to_cygwin ()
 {
-  $opt_debug
-  func_to_host_file_result="$1"
+  $debug_cmd
+
+  func_to_host_file_result=$1
   if test -n "$1"; then
     # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
     func_convert_core_file_wine_to_w32 "$1"
     func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
-    func_to_host_file_result="$func_cygpath_result"
+    func_to_host_file_result=$func_cygpath_result
   fi
   func_convert_file_check "$1" "$func_to_host_file_result"
 }
@@ -1781,7 +3072,7 @@ func_convert_file_nix_to_cygwin ()
 #############################################
 # $build to $host PATH CONVERSION FUNCTIONS #
 #############################################
-# invoked via `$to_host_path_cmd ARG'
+# invoked via '$to_host_path_cmd ARG'
 #
 # In each case, ARG is the path to be converted from $build to $host format.
 # The result will be available in $func_to_host_path_result.
@@ -1805,10 +3096,11 @@ func_convert_file_nix_to_cygwin ()
 to_host_path_cmd=
 func_init_to_host_path_cmd ()
 {
-  $opt_debug
+  $debug_cmd
+
   if test -z "$to_host_path_cmd"; then
     func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
-    to_host_path_cmd="func_convert_path_${func_stripname_result}"
+    to_host_path_cmd=func_convert_path_$func_stripname_result
   fi
 }
 
@@ -1818,7 +3110,8 @@ func_init_to_host_path_cmd ()
 # in func_to_host_path_result.
 func_to_host_path ()
 {
-  $opt_debug
+  $debug_cmd
+
   func_init_to_host_path_cmd
   $to_host_path_cmd "$1"
 }
@@ -1829,7 +3122,7 @@ func_to_host_path ()
 # Copy ARG to func_to_host_path_result.
 func_convert_path_noop ()
 {
-  func_to_host_path_result="$1"
+  func_to_host_path_result=$1
 }
 # end func_convert_path_noop
 
@@ -1840,8 +3133,9 @@ func_convert_path_noop ()
 # func_to_host_path_result.
 func_convert_path_msys_to_w32 ()
 {
-  $opt_debug
-  func_to_host_path_result="$1"
+  $debug_cmd
+
+  func_to_host_path_result=$1
   if test -n "$1"; then
     # Remove leading and trailing path separator characters from ARG.  MSYS
     # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
@@ -1849,7 +3143,7 @@ func_convert_path_msys_to_w32 ()
     func_stripname : : "$1"
     func_to_host_path_tmp1=$func_stripname_result
     func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
-    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result=$func_convert_core_msys_to_w32_result
     func_convert_path_check : ";" \
       "$func_to_host_path_tmp1" "$func_to_host_path_result"
     func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
@@ -1863,8 +3157,9 @@ func_convert_path_msys_to_w32 ()
 # func_to_host_file_result.
 func_convert_path_cygwin_to_w32 ()
 {
-  $opt_debug
-  func_to_host_path_result="$1"
+  $debug_cmd
+
+  func_to_host_path_result=$1
   if test -n "$1"; then
     # See func_convert_path_msys_to_w32:
     func_stripname : : "$1"
@@ -1883,14 +3178,15 @@ func_convert_path_cygwin_to_w32 ()
 # a working winepath.  Returns result in func_to_host_file_result.
 func_convert_path_nix_to_w32 ()
 {
-  $opt_debug
-  func_to_host_path_result="$1"
+  $debug_cmd
+
+  func_to_host_path_result=$1
   if test -n "$1"; then
     # See func_convert_path_msys_to_w32:
     func_stripname : : "$1"
     func_to_host_path_tmp1=$func_stripname_result
     func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
-    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result
     func_convert_path_check : ";" \
       "$func_to_host_path_tmp1" "$func_to_host_path_result"
     func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
@@ -1904,15 +3200,16 @@ func_convert_path_nix_to_w32 ()
 # Returns result in func_to_host_file_result.
 func_convert_path_msys_to_cygwin ()
 {
-  $opt_debug
-  func_to_host_path_result="$1"
+  $debug_cmd
+
+  func_to_host_path_result=$1
   if test -n "$1"; then
     # See func_convert_path_msys_to_w32:
     func_stripname : : "$1"
     func_to_host_path_tmp1=$func_stripname_result
     func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
     func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
-    func_to_host_path_result="$func_cygpath_result"
+    func_to_host_path_result=$func_cygpath_result
     func_convert_path_check : : \
       "$func_to_host_path_tmp1" "$func_to_host_path_result"
     func_convert_path_front_back_pathsep ":*" "*:" : "$1"
@@ -1927,8 +3224,9 @@ func_convert_path_msys_to_cygwin ()
 # func_to_host_file_result.
 func_convert_path_nix_to_cygwin ()
 {
-  $opt_debug
-  func_to_host_path_result="$1"
+  $debug_cmd
+
+  func_to_host_path_result=$1
   if test -n "$1"; then
     # Remove leading and trailing path separator characters from
     # ARG. msys behavior is inconsistent here, cygpath turns them
@@ -1937,7 +3235,7 @@ func_convert_path_nix_to_cygwin ()
     func_to_host_path_tmp1=$func_stripname_result
     func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
     func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
-    func_to_host_path_result="$func_cygpath_result"
+    func_to_host_path_result=$func_cygpath_result
     func_convert_path_check : : \
       "$func_to_host_path_tmp1" "$func_to_host_path_result"
     func_convert_path_front_back_pathsep ":*" "*:" : "$1"
@@ -1946,13 +3244,31 @@ func_convert_path_nix_to_cygwin ()
 # end func_convert_path_nix_to_cygwin
 
 
+# func_dll_def_p FILE
+# True iff FILE is a Windows DLL '.def' file.
+# Keep in sync with _LT_DLL_DEF_P in libtool.m4
+func_dll_def_p ()
+{
+  $debug_cmd
+
+  func_dll_def_p_tmp=`$SED -n \
+    -e 's/^[	 ]*//' \
+    -e '/^\(;.*\)*$/d' \
+    -e 's/^\(EXPORTS\|LIBRARY\)\([	 ].*\)*$/DEF/p' \
+    -e q \
+    "$1"`
+  test DEF = "$func_dll_def_p_tmp"
+}
+
+
 # func_mode_compile arg...
 func_mode_compile ()
 {
-    $opt_debug
+    $debug_cmd
+
     # Get the compilation command and the source file.
     base_compile=
-    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
+    srcfile=$nonopt  #  always keep a non-empty value in "srcfile"
     suppress_opt=yes
     suppress_output=
     arg_mode=normal
@@ -1965,12 +3281,12 @@ func_mode_compile ()
       case $arg_mode in
       arg  )
 	# do not "continue".  Instead, add this to base_compile
-	lastarg="$arg"
+	lastarg=$arg
 	arg_mode=normal
 	;;
 
       target )
-	libobj="$arg"
+	libobj=$arg
 	arg_mode=normal
 	continue
 	;;
@@ -1980,7 +3296,7 @@ func_mode_compile ()
 	case $arg in
 	-o)
 	  test -n "$libobj" && \
-	    func_fatal_error "you cannot specify \`-o' more than once"
+	    func_fatal_error "you cannot specify '-o' more than once"
 	  arg_mode=target
 	  continue
 	  ;;
@@ -2009,12 +3325,12 @@ func_mode_compile ()
 	  func_stripname '-Wc,' '' "$arg"
 	  args=$func_stripname_result
 	  lastarg=
-	  save_ifs="$IFS"; IFS=','
+	  save_ifs=$IFS; IFS=,
 	  for arg in $args; do
-	    IFS="$save_ifs"
+	    IFS=$save_ifs
 	    func_append_quoted lastarg "$arg"
 	  done
-	  IFS="$save_ifs"
+	  IFS=$save_ifs
 	  func_stripname ' ' '' "$lastarg"
 	  lastarg=$func_stripname_result
 
@@ -2027,8 +3343,8 @@ func_mode_compile ()
 	  # Accept the current argument as the source file.
 	  # The previous "srcfile" becomes the current argument.
 	  #
-	  lastarg="$srcfile"
-	  srcfile="$arg"
+	  lastarg=$srcfile
+	  srcfile=$arg
 	  ;;
 	esac  #  case $arg
 	;;
@@ -2043,13 +3359,13 @@ func_mode_compile ()
       func_fatal_error "you must specify an argument for -Xcompile"
       ;;
     target)
-      func_fatal_error "you must specify a target with \`-o'"
+      func_fatal_error "you must specify a target with '-o'"
       ;;
     *)
       # Get the name of the library object.
       test -z "$libobj" && {
 	func_basename "$srcfile"
-	libobj="$func_basename_result"
+	libobj=$func_basename_result
       }
       ;;
     esac
@@ -2069,7 +3385,7 @@ func_mode_compile ()
     case $libobj in
     *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
     *)
-      func_fatal_error "cannot determine name of library object from \`$libobj'"
+      func_fatal_error "cannot determine name of library object from '$libobj'"
       ;;
     esac
 
@@ -2078,8 +3394,8 @@ func_mode_compile ()
     for arg in $later; do
       case $arg in
       -shared)
-	test "$build_libtool_libs" != yes && \
-	  func_fatal_configuration "can not build a shared library"
+	test yes = "$build_libtool_libs" \
+	  || func_fatal_configuration "cannot build a shared library"
 	build_old_libs=no
 	continue
 	;;
@@ -2105,17 +3421,17 @@ func_mode_compile ()
     func_quote_for_eval "$libobj"
     test "X$libobj" != "X$func_quote_for_eval_result" \
       && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
-      && func_warning "libobj name \`$libobj' may not contain shell special characters."
+      && func_warning "libobj name '$libobj' may not contain shell special characters."
     func_dirname_and_basename "$obj" "/" ""
-    objname="$func_basename_result"
-    xdir="$func_dirname_result"
-    lobj=${xdir}$objdir/$objname
+    objname=$func_basename_result
+    xdir=$func_dirname_result
+    lobj=$xdir$objdir/$objname
 
     test -z "$base_compile" && \
       func_fatal_help "you must specify a compilation command"
 
     # Delete any leftover library objects.
-    if test "$build_old_libs" = yes; then
+    if test yes = "$build_old_libs"; then
       removelist="$obj $lobj $libobj ${libobj}T"
     else
       removelist="$lobj $libobj ${libobj}T"
@@ -2127,16 +3443,16 @@ func_mode_compile ()
       pic_mode=default
       ;;
     esac
-    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
+    if test no = "$pic_mode" && test pass_all != "$deplibs_check_method"; then
       # non-PIC code in shared libraries is not supported
       pic_mode=default
     fi
 
     # Calculate the filename of the output object if compiler does
     # not support -o with -c
-    if test "$compiler_c_o" = no; then
-      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
-      lockfile="$output_obj.lock"
+    if test no = "$compiler_c_o"; then
+      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.$objext
+      lockfile=$output_obj.lock
     else
       output_obj=
       need_locks=no
@@ -2145,12 +3461,12 @@ func_mode_compile ()
 
     # Lock this critical section if it is needed
     # We use this script file to make the link, it avoids creating a new file
-    if test "$need_locks" = yes; then
+    if test yes = "$need_locks"; then
       until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
 	func_echo "Waiting for $lockfile to be removed"
 	sleep 2
       done
-    elif test "$need_locks" = warn; then
+    elif test warn = "$need_locks"; then
       if test -f "$lockfile"; then
 	$ECHO "\
 *** ERROR, $lockfile exists and contains:
@@ -2158,7 +3474,7 @@ func_mode_compile ()
 
 This indicates that another process is trying to use the same
 temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
+your compiler does not support '-c' and '-o' together.  If you
 repeat this compilation, it may succeed, by chance, but you had better
 avoid parallel builds (make -j) in this platform, or get a better
 compiler."
@@ -2180,11 +3496,11 @@ compiler."
     qsrcfile=$func_quote_for_eval_result
 
     # Only build a PIC object if we are building libtool libraries.
-    if test "$build_libtool_libs" = yes; then
+    if test yes = "$build_libtool_libs"; then
       # Without this assignment, base_compile gets emptied.
       fbsd_hideous_sh_bug=$base_compile
 
-      if test "$pic_mode" != no; then
+      if test no != "$pic_mode"; then
 	command="$base_compile $qsrcfile $pic_flag"
       else
 	# Don't build PIC code
@@ -2201,7 +3517,7 @@ compiler."
       func_show_eval_locale "$command"	\
           'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
 
-      if test "$need_locks" = warn &&
+      if test warn = "$need_locks" &&
 	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
 	$ECHO "\
 *** ERROR, $lockfile contains:
@@ -2212,7 +3528,7 @@ $srcfile
 
 This indicates that another process is trying to use the same
 temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
+your compiler does not support '-c' and '-o' together.  If you
 repeat this compilation, it may succeed, by chance, but you had better
 avoid parallel builds (make -j) in this platform, or get a better
 compiler."
@@ -2228,20 +3544,20 @@ compiler."
       fi
 
       # Allow error messages only from the first compilation.
-      if test "$suppress_opt" = yes; then
+      if test yes = "$suppress_opt"; then
 	suppress_output=' >/dev/null 2>&1'
       fi
     fi
 
     # Only build a position-dependent object if we build old libraries.
-    if test "$build_old_libs" = yes; then
-      if test "$pic_mode" != yes; then
+    if test yes = "$build_old_libs"; then
+      if test yes != "$pic_mode"; then
 	# Don't build PIC code
 	command="$base_compile $qsrcfile$pie_flag"
       else
 	command="$base_compile $qsrcfile $pic_flag"
       fi
-      if test "$compiler_c_o" = yes; then
+      if test yes = "$compiler_c_o"; then
 	func_append command " -o $obj"
       fi
 
@@ -2250,7 +3566,7 @@ compiler."
       func_show_eval_locale "$command" \
         '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
 
-      if test "$need_locks" = warn &&
+      if test warn = "$need_locks" &&
 	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
 	$ECHO "\
 *** ERROR, $lockfile contains:
@@ -2261,7 +3577,7 @@ $srcfile
 
 This indicates that another process is trying to use the same
 temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
+your compiler does not support '-c' and '-o' together.  If you
 repeat this compilation, it may succeed, by chance, but you had better
 avoid parallel builds (make -j) in this platform, or get a better
 compiler."
@@ -2281,7 +3597,7 @@ compiler."
       func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
 
       # Unlock the critical section if it was locked
-      if test "$need_locks" != no; then
+      if test no != "$need_locks"; then
 	removelist=$lockfile
         $RM "$lockfile"
       fi
@@ -2291,7 +3607,7 @@ compiler."
 }
 
 $opt_help || {
-  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
+  test compile = "$opt_mode" && func_mode_compile ${1+"$@"}
 }
 
 func_mode_help ()
@@ -2311,7 +3627,7 @@ func_mode_help ()
 Remove files from the build directory.
 
 RM is the name of the program to use to delete files associated with each FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed
 to RM.
 
 If FILE is a libtool library, object or program, all the files associated
@@ -2330,16 +3646,16 @@ This mode accepts the following additional options:
   -no-suppress      do not suppress compiler output for multiple passes
   -prefer-pic       try to build PIC objects only
   -prefer-non-pic   try to build non-PIC objects only
-  -shared           do not build a \`.o' file suitable for static linking
-  -static           only build a \`.o' file suitable for static linking
+  -shared           do not build a '.o' file suitable for static linking
+  -static           only build a '.o' file suitable for static linking
   -Wc,FLAG          pass FLAG directly to the compiler
 
-COMPILE-COMMAND is a command to be used in creating a \`standard' object file
+COMPILE-COMMAND is a command to be used in creating a 'standard' object file
 from the given SOURCEFILE.
 
 The output file name is determined by removing the directory component from
-SOURCEFILE, then substituting the C source code suffix \`.c' with the
-library object suffix, \`.lo'."
+SOURCEFILE, then substituting the C source code suffix '.c' with the
+library object suffix, '.lo'."
         ;;
 
       execute)
@@ -2352,7 +3668,7 @@ This mode accepts the following additional options:
 
   -dlopen FILE      add the directory containing FILE to the library path
 
-This mode sets the library path environment variable according to \`-dlopen'
+This mode sets the library path environment variable according to '-dlopen'
 flags.
 
 If any of the ARGS are libtool executable wrappers, then they are translated
@@ -2371,7 +3687,7 @@ Complete the installation of libtool libraries.
 Each LIBDIR is a directory that contains libtool libraries.
 
 The commands that this mode executes may require superuser privileges.  Use
-the \`--dry-run' option if you just want to see what would be executed."
+the '--dry-run' option if you just want to see what would be executed."
         ;;
 
       install)
@@ -2381,7 +3697,7 @@ the \`--dry-run' option if you just want to see what would be executed."
 Install executables or libraries.
 
 INSTALL-COMMAND is the installation command.  The first component should be
-either the \`install' or \`cp' program.
+either the 'install' or 'cp' program.
 
 The following components of INSTALL-COMMAND are treated specially:
 
@@ -2407,7 +3723,7 @@ The following components of LINK-COMMAND are treated specially:
   -avoid-version    do not add a version suffix if possible
   -bindir BINDIR    specify path to binaries directory (for systems where
                     libraries must be found in the PATH setting at runtime)
-  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
+  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime
   -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
   -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
   -export-symbols SYMFILE
@@ -2421,7 +3737,8 @@ The following components of LINK-COMMAND are treated specially:
   -no-install       link a not-installable executable
   -no-undefined     declare that a library does not refer to external symbols
   -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
-  -objectlist FILE  Use a list of object files found in FILE to specify objects
+  -objectlist FILE  use a list of object files found in FILE to specify objects
+  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)
   -precious-files-regex REGEX
                     don't remove output files matching REGEX
   -release RELEASE  specify package release information
@@ -2441,20 +3758,20 @@ The following components of LINK-COMMAND are treated specially:
   -Xlinker FLAG     pass linker-specific FLAG directly to the linker
   -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
 
-All other options (arguments beginning with \`-') are ignored.
+All other options (arguments beginning with '-') are ignored.
 
-Every other argument is treated as a filename.  Files ending in \`.la' are
+Every other argument is treated as a filename.  Files ending in '.la' are
 treated as uninstalled libtool libraries, other files are standard or library
 object files.
 
-If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
-only library objects (\`.lo' files) may be specified, and \`-rpath' is
+If the OUTPUT-FILE ends in '.la', then a libtool library is created,
+only library objects ('.lo' files) may be specified, and '-rpath' is
 required, except when creating a convenience library.
 
-If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
-using \`ar' and \`ranlib', or on Windows using \`lib'.
+If OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created
+using 'ar' and 'ranlib', or on Windows using 'lib'.
 
-If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
+If OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file
 is created, otherwise an executable program is created."
         ;;
 
@@ -2465,7 +3782,7 @@ is created, otherwise an executable program is created."
 Remove libraries from an installation directory.
 
 RM is the name of the program to use to delete files associated with each FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
+(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed
 to RM.
 
 If FILE is a libtool library, all the files associated with it are deleted.
@@ -2473,17 +3790,17 @@ Otherwise, only FILE itself is deleted using RM."
         ;;
 
       *)
-        func_fatal_help "invalid operation mode \`$opt_mode'"
+        func_fatal_help "invalid operation mode '$opt_mode'"
         ;;
     esac
 
     echo
-    $ECHO "Try \`$progname --help' for more information about other modes."
+    $ECHO "Try '$progname --help' for more information about other modes."
 }
 
 # Now that we've collected a possible --mode arg, show help if necessary
 if $opt_help; then
-  if test "$opt_help" = :; then
+  if test : = "$opt_help"; then
     func_mode_help
   else
     {
@@ -2491,7 +3808,7 @@ if $opt_help; then
       for opt_mode in compile link execute install finish uninstall clean; do
 	func_mode_help
       done
-    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'
     {
       func_help noexit
       for opt_mode in compile link execute install finish uninstall clean; do
@@ -2499,7 +3816,7 @@ if $opt_help; then
 	func_mode_help
       done
     } |
-    sed '1d
+    $SED '1d
       /^When reporting/,/^Report/{
 	H
 	d
@@ -2516,16 +3833,17 @@ fi
 # func_mode_execute arg...
 func_mode_execute ()
 {
-    $opt_debug
+    $debug_cmd
+
     # The first argument is the command name.
-    cmd="$nonopt"
+    cmd=$nonopt
     test -z "$cmd" && \
       func_fatal_help "you must specify a COMMAND"
 
     # Handle -dlopen flags immediately.
     for file in $opt_dlopen; do
       test -f "$file" \
-	|| func_fatal_help "\`$file' is not a file"
+	|| func_fatal_help "'$file' is not a file"
 
       dir=
       case $file in
@@ -2535,7 +3853,7 @@ func_mode_execute ()
 
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
-	  || func_fatal_help "\`$lib' is not a valid libtool archive"
+	  || func_fatal_help "'$lib' is not a valid libtool archive"
 
 	# Read the libtool library.
 	dlname=
@@ -2546,18 +3864,18 @@ func_mode_execute ()
 	if test -z "$dlname"; then
 	  # Warn if it was a shared library.
 	  test -n "$library_names" && \
-	    func_warning "\`$file' was not linked with \`-export-dynamic'"
+	    func_warning "'$file' was not linked with '-export-dynamic'"
 	  continue
 	fi
 
 	func_dirname "$file" "" "."
-	dir="$func_dirname_result"
+	dir=$func_dirname_result
 
 	if test -f "$dir/$objdir/$dlname"; then
 	  func_append dir "/$objdir"
 	else
 	  if test ! -f "$dir/$dlname"; then
-	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
+	    func_fatal_error "cannot find '$dlname' in '$dir' or '$dir/$objdir'"
 	  fi
 	fi
 	;;
@@ -2565,18 +3883,18 @@ func_mode_execute ()
       *.lo)
 	# Just add the directory containing the .lo file.
 	func_dirname "$file" "" "."
-	dir="$func_dirname_result"
+	dir=$func_dirname_result
 	;;
 
       *)
-	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
+	func_warning "'-dlopen' is ignored for non-libtool libraries and objects"
 	continue
 	;;
       esac
 
       # Get the absolute pathname.
       absdir=`cd "$dir" && pwd`
-      test -n "$absdir" && dir="$absdir"
+      test -n "$absdir" && dir=$absdir
 
       # Now add the directory to shlibpath_var.
       if eval "test -z \"\$$shlibpath_var\""; then
@@ -2588,7 +3906,7 @@ func_mode_execute ()
 
     # This variable tells wrapper scripts just to set shlibpath_var
     # rather than running their programs.
-    libtool_execute_magic="$magic"
+    libtool_execute_magic=$magic
 
     # Check if any of the arguments is a wrapper script.
     args=
@@ -2601,12 +3919,12 @@ func_mode_execute ()
 	if func_ltwrapper_script_p "$file"; then
 	  func_source "$file"
 	  # Transform arg to wrapped name.
-	  file="$progdir/$program"
+	  file=$progdir/$program
 	elif func_ltwrapper_executable_p "$file"; then
 	  func_ltwrapper_scriptname "$file"
 	  func_source "$func_ltwrapper_scriptname_result"
 	  # Transform arg to wrapped name.
-	  file="$progdir/$program"
+	  file=$progdir/$program
 	fi
 	;;
       esac
@@ -2614,7 +3932,15 @@ func_mode_execute ()
       func_append_quoted args "$file"
     done
 
-    if test "X$opt_dry_run" = Xfalse; then
+    if $opt_dry_run; then
+      # Display what would be done.
+      if test -n "$shlibpath_var"; then
+	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
+	echo "export $shlibpath_var"
+      fi
+      $ECHO "$cmd$args"
+      exit $EXIT_SUCCESS
+    else
       if test -n "$shlibpath_var"; then
 	# Export the shlibpath_var.
 	eval "export $shlibpath_var"
@@ -2631,25 +3957,18 @@ func_mode_execute ()
       done
 
       # Now prepare to actually exec the command.
-      exec_cmd="\$cmd$args"
-    else
-      # Display what would be done.
-      if test -n "$shlibpath_var"; then
-	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
-	echo "export $shlibpath_var"
-      fi
-      $ECHO "$cmd$args"
-      exit $EXIT_SUCCESS
+      exec_cmd=\$cmd$args
     fi
 }
 
-test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
+test execute = "$opt_mode" && func_mode_execute ${1+"$@"}
 
 
 # func_mode_finish arg...
 func_mode_finish ()
 {
-    $opt_debug
+    $debug_cmd
+
     libs=
     libdirs=
     admincmds=
@@ -2663,11 +3982,11 @@ func_mode_finish ()
 	if func_lalib_unsafe_p "$opt"; then
 	  func_append libs " $opt"
 	else
-	  func_warning "\`$opt' is not a valid libtool archive"
+	  func_warning "'$opt' is not a valid libtool archive"
 	fi
 
       else
-	func_fatal_error "invalid argument \`$opt'"
+	func_fatal_error "invalid argument '$opt'"
       fi
     done
 
@@ -2682,12 +4001,12 @@ func_mode_finish ()
       # Remove sysroot references
       if $opt_dry_run; then
         for lib in $libs; do
-          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
+          echo "removing references to $lt_sysroot and '=' prefixes from $lib"
         done
       else
         tmpdir=`func_mktempdir`
         for lib in $libs; do
-	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
+	  $SED -e "$sysroot_cmd s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
 	    > $tmpdir/tmp-la
 	  mv -f $tmpdir/tmp-la $lib
 	done
@@ -2712,7 +4031,7 @@ func_mode_finish ()
     fi
 
     # Exit here if they wanted silent mode.
-    $opt_silent && exit $EXIT_SUCCESS
+    $opt_quiet && exit $EXIT_SUCCESS
 
     if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
       echo "----------------------------------------------------------------------"
@@ -2723,27 +4042,27 @@ func_mode_finish ()
       echo
       echo "If you ever happen to want to link against installed libraries"
       echo "in a given directory, LIBDIR, you must either use libtool, and"
-      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
+      echo "specify the full pathname of the library, or use the '-LLIBDIR'"
       echo "flag during linking and do at least one of the following:"
       if test -n "$shlibpath_var"; then
-	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "   - add LIBDIR to the '$shlibpath_var' environment variable"
 	echo "     during execution"
       fi
       if test -n "$runpath_var"; then
-	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "   - add LIBDIR to the '$runpath_var' environment variable"
 	echo "     during linking"
       fi
       if test -n "$hardcode_libdir_flag_spec"; then
 	libdir=LIBDIR
 	eval flag=\"$hardcode_libdir_flag_spec\"
 
-	$ECHO "   - use the \`$flag' linker flag"
+	$ECHO "   - use the '$flag' linker flag"
       fi
       if test -n "$admincmds"; then
 	$ECHO "   - have your system administrator run these commands:$admincmds"
       fi
       if test -f /etc/ld.so.conf; then
-	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
+	echo "   - have your system administrator add LIBDIR to '/etc/ld.so.conf'"
       fi
       echo
 
@@ -2762,18 +4081,20 @@ func_mode_finish ()
     exit $EXIT_SUCCESS
 }
 
-test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
+test finish = "$opt_mode" && func_mode_finish ${1+"$@"}
 
 
 # func_mode_install arg...
 func_mode_install ()
 {
-    $opt_debug
+    $debug_cmd
+
     # There may be an optional sh(1) argument at the beginning of
     # install_prog (especially on Windows NT).
-    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
+    if test "$SHELL" = "$nonopt" || test /bin/sh = "$nonopt" ||
        # Allow the use of GNU shtool's install command.
-       case $nonopt in *shtool*) :;; *) false;; esac; then
+       case $nonopt in *shtool*) :;; *) false;; esac
+    then
       # Aesthetically quote it.
       func_quote_for_eval "$nonopt"
       install_prog="$func_quote_for_eval_result "
@@ -2800,7 +4121,7 @@ func_mode_install ()
     opts=
     prev=
     install_type=
-    isdir=no
+    isdir=false
     stripme=
     no_mode=:
     for arg
@@ -2813,7 +4134,7 @@ func_mode_install ()
       fi
 
       case $arg in
-      -d) isdir=yes ;;
+      -d) isdir=: ;;
       -f)
 	if $install_cp; then :; else
 	  prev=$arg
@@ -2831,7 +4152,7 @@ func_mode_install ()
       *)
 	# If the previous option needed an argument, then skip it.
 	if test -n "$prev"; then
-	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
+	  if test X-m = "X$prev" && test -n "$install_override_mode"; then
 	    arg2=$install_override_mode
 	    no_mode=false
 	  fi
@@ -2856,7 +4177,7 @@ func_mode_install ()
       func_fatal_help "you must specify an install program"
 
     test -n "$prev" && \
-      func_fatal_help "the \`$prev' option requires an argument"
+      func_fatal_help "the '$prev' option requires an argument"
 
     if test -n "$install_override_mode" && $no_mode; then
       if $install_cp; then :; else
@@ -2878,19 +4199,19 @@ func_mode_install ()
     dest=$func_stripname_result
 
     # Check to see that the destination is a directory.
-    test -d "$dest" && isdir=yes
-    if test "$isdir" = yes; then
-      destdir="$dest"
+    test -d "$dest" && isdir=:
+    if $isdir; then
+      destdir=$dest
       destname=
     else
       func_dirname_and_basename "$dest" "" "."
-      destdir="$func_dirname_result"
-      destname="$func_basename_result"
+      destdir=$func_dirname_result
+      destname=$func_basename_result
 
       # Not a directory, so check to see that there is only one file specified.
       set dummy $files; shift
       test "$#" -gt 1 && \
-	func_fatal_help "\`$dest' is not a directory"
+	func_fatal_help "'$dest' is not a directory"
     fi
     case $destdir in
     [\\/]* | [A-Za-z]:[\\/]*) ;;
@@ -2899,7 +4220,7 @@ func_mode_install ()
 	case $file in
 	*.lo) ;;
 	*)
-	  func_fatal_help "\`$destdir' must be an absolute directory name"
+	  func_fatal_help "'$destdir' must be an absolute directory name"
 	  ;;
 	esac
       done
@@ -2908,7 +4229,7 @@ func_mode_install ()
 
     # This variable tells wrapper scripts just to set variables rather
     # than running their programs.
-    libtool_install_magic="$magic"
+    libtool_install_magic=$magic
 
     staticlibs=
     future_libdirs=
@@ -2928,7 +4249,7 @@ func_mode_install ()
 
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$file" \
-	  || func_fatal_help "\`$file' is not a valid libtool archive"
+	  || func_fatal_help "'$file' is not a valid libtool archive"
 
 	library_names=
 	old_library=
@@ -2950,7 +4271,7 @@ func_mode_install ()
 	fi
 
 	func_dirname "$file" "/" ""
-	dir="$func_dirname_result"
+	dir=$func_dirname_result
 	func_append dir "$objdir"
 
 	if test -n "$relink_command"; then
@@ -2964,7 +4285,7 @@ func_mode_install ()
 	  # are installed into $libdir/../bin (currently, that works fine)
 	  # but it's something to keep an eye on.
 	  test "$inst_prefix_dir" = "$destdir" && \
-	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
+	    func_fatal_error "error: cannot install '$file' to a directory not ending in $libdir"
 
 	  if test -n "$inst_prefix_dir"; then
 	    # Stick the inst_prefix_dir data into the link command.
@@ -2973,29 +4294,36 @@ func_mode_install ()
 	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
 	  fi
 
-	  func_warning "relinking \`$file'"
+	  func_warning "relinking '$file'"
 	  func_show_eval "$relink_command" \
-	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
+	    'func_fatal_error "error: relink '\''$file'\'' with the above command before installing it"'
 	fi
 
 	# See the names of the shared library.
 	set dummy $library_names; shift
 	if test -n "$1"; then
-	  realname="$1"
+	  realname=$1
 	  shift
 
-	  srcname="$realname"
-	  test -n "$relink_command" && srcname="$realname"T
+	  srcname=$realname
+	  test -n "$relink_command" && srcname=${realname}T
 
 	  # Install the shared library and build the symlinks.
 	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
 	      'exit $?'
-	  tstripme="$stripme"
+	  tstripme=$stripme
 	  case $host_os in
 	  cygwin* | mingw* | pw32* | cegcc*)
 	    case $realname in
 	    *.dll.a)
-	      tstripme=""
+	      tstripme=
+	      ;;
+	    esac
+	    ;;
+	  os2*)
+	    case $realname in
+	    *_dll.a)
+	      tstripme=
 	      ;;
 	    esac
 	    ;;
@@ -3006,7 +4334,7 @@ func_mode_install ()
 
 	  if test "$#" -gt 0; then
 	    # Delete the old symlinks, and create new ones.
-	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # Try 'ln -sf' first, because the 'ln' binary might depend on
 	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
 	    # so we also need to try rm && ln -s.
 	    for linkname
@@ -3017,14 +4345,14 @@ func_mode_install ()
 	  fi
 
 	  # Do each command in the postinstall commands.
-	  lib="$destdir/$realname"
+	  lib=$destdir/$realname
 	  func_execute_cmds "$postinstall_cmds" 'exit $?'
 	fi
 
 	# Install the pseudo-library for information purposes.
 	func_basename "$file"
-	name="$func_basename_result"
-	instname="$dir/$name"i
+	name=$func_basename_result
+	instname=$dir/${name}i
 	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
 
 	# Maybe install the static library, too.
@@ -3036,11 +4364,11 @@ func_mode_install ()
 
 	# Figure out destination file name, if it wasn't already specified.
 	if test -n "$destname"; then
-	  destfile="$destdir/$destname"
+	  destfile=$destdir/$destname
 	else
 	  func_basename "$file"
-	  destfile="$func_basename_result"
-	  destfile="$destdir/$destfile"
+	  destfile=$func_basename_result
+	  destfile=$destdir/$destfile
 	fi
 
 	# Deduce the name of the destination old-style object file.
@@ -3050,11 +4378,11 @@ func_mode_install ()
 	  staticdest=$func_lo2o_result
 	  ;;
 	*.$objext)
-	  staticdest="$destfile"
+	  staticdest=$destfile
 	  destfile=
 	  ;;
 	*)
-	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
+	  func_fatal_help "cannot copy a libtool object to '$destfile'"
 	  ;;
 	esac
 
@@ -3063,7 +4391,7 @@ func_mode_install ()
 	  func_show_eval "$install_prog $file $destfile" 'exit $?'
 
 	# Install the old object if enabled.
-	if test "$build_old_libs" = yes; then
+	if test yes = "$build_old_libs"; then
 	  # Deduce the name of the old-style object file.
 	  func_lo2o "$file"
 	  staticobj=$func_lo2o_result
@@ -3075,23 +4403,23 @@ func_mode_install ()
       *)
 	# Figure out destination file name, if it wasn't already specified.
 	if test -n "$destname"; then
-	  destfile="$destdir/$destname"
+	  destfile=$destdir/$destname
 	else
 	  func_basename "$file"
-	  destfile="$func_basename_result"
-	  destfile="$destdir/$destfile"
+	  destfile=$func_basename_result
+	  destfile=$destdir/$destfile
 	fi
 
 	# If the file is missing, and there is a .exe on the end, strip it
 	# because it is most likely a libtool script we actually want to
 	# install
-	stripped_ext=""
+	stripped_ext=
 	case $file in
 	  *.exe)
 	    if test ! -f "$file"; then
 	      func_stripname '' '.exe' "$file"
 	      file=$func_stripname_result
-	      stripped_ext=".exe"
+	      stripped_ext=.exe
 	    fi
 	    ;;
 	esac
@@ -3119,19 +4447,19 @@ func_mode_install ()
 
 	  # Check the variables that should have been set.
 	  test -z "$generated_by_libtool_version" && \
-	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
+	    func_fatal_error "invalid libtool wrapper script '$wrapper'"
 
-	  finalize=yes
+	  finalize=:
 	  for lib in $notinst_deplibs; do
 	    # Check to see that each library is installed.
 	    libdir=
 	    if test -f "$lib"; then
 	      func_source "$lib"
 	    fi
-	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
+	    libfile=$libdir/`$ECHO "$lib" | $SED 's%^.*/%%g'`
 	    if test -n "$libdir" && test ! -f "$libfile"; then
-	      func_warning "\`$lib' has not been installed in \`$libdir'"
-	      finalize=no
+	      func_warning "'$lib' has not been installed in '$libdir'"
+	      finalize=false
 	    fi
 	  done
 
@@ -3139,29 +4467,29 @@ func_mode_install ()
 	  func_source "$wrapper"
 
 	  outputname=
-	  if test "$fast_install" = no && test -n "$relink_command"; then
+	  if test no = "$fast_install" && test -n "$relink_command"; then
 	    $opt_dry_run || {
-	      if test "$finalize" = yes; then
+	      if $finalize; then
 	        tmpdir=`func_mktempdir`
 		func_basename "$file$stripped_ext"
-		file="$func_basename_result"
-	        outputname="$tmpdir/$file"
+		file=$func_basename_result
+	        outputname=$tmpdir/$file
 	        # Replace the output file specification.
 	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
 
-	        $opt_silent || {
+	        $opt_quiet || {
 	          func_quote_for_expand "$relink_command"
 		  eval "func_echo $func_quote_for_expand_result"
 	        }
 	        if eval "$relink_command"; then :
 	          else
-		  func_error "error: relink \`$file' with the above command before installing it"
+		  func_error "error: relink '$file' with the above command before installing it"
 		  $opt_dry_run || ${RM}r "$tmpdir"
 		  continue
 	        fi
-	        file="$outputname"
+	        file=$outputname
 	      else
-	        func_warning "cannot relink \`$file'"
+	        func_warning "cannot relink '$file'"
 	      fi
 	    }
 	  else
@@ -3198,10 +4526,10 @@ func_mode_install ()
 
     for file in $staticlibs; do
       func_basename "$file"
-      name="$func_basename_result"
+      name=$func_basename_result
 
       # Set up the ranlib parameters.
-      oldlib="$destdir/$name"
+      oldlib=$destdir/$name
       func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
       tool_oldlib=$func_to_tool_file_result
 
@@ -3216,18 +4544,18 @@ func_mode_install ()
     done
 
     test -n "$future_libdirs" && \
-      func_warning "remember to run \`$progname --finish$future_libdirs'"
+      func_warning "remember to run '$progname --finish$future_libdirs'"
 
     if test -n "$current_libdirs"; then
       # Maybe just do a dry run.
       $opt_dry_run && current_libdirs=" -n$current_libdirs"
-      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
+      exec_cmd='$SHELL "$progpath" $preserve_args --finish$current_libdirs'
     else
       exit $EXIT_SUCCESS
     fi
 }
 
-test "$opt_mode" = install && func_mode_install ${1+"$@"}
+test install = "$opt_mode" && func_mode_install ${1+"$@"}
 
 
 # func_generate_dlsyms outputname originator pic_p
@@ -3235,16 +4563,17 @@ test "$opt_mode" = install && func_mode_install ${1+"$@"}
 # a dlpreopen symbol table.
 func_generate_dlsyms ()
 {
-    $opt_debug
-    my_outputname="$1"
-    my_originator="$2"
-    my_pic_p="${3-no}"
-    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
+    $debug_cmd
+
+    my_outputname=$1
+    my_originator=$2
+    my_pic_p=${3-false}
+    my_prefix=`$ECHO "$my_originator" | $SED 's%[^a-zA-Z0-9]%_%g'`
     my_dlsyms=
 
-    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
+    if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then
       if test -n "$NM" && test -n "$global_symbol_pipe"; then
-	my_dlsyms="${my_outputname}S.c"
+	my_dlsyms=${my_outputname}S.c
       else
 	func_error "not configured to extract global symbols from dlpreopened files"
       fi
@@ -3255,7 +4584,7 @@ func_generate_dlsyms ()
       "") ;;
       *.c)
 	# Discover the nlist of each of the dlfiles.
-	nlist="$output_objdir/${my_outputname}.nm"
+	nlist=$output_objdir/$my_outputname.nm
 
 	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
 
@@ -3263,34 +4592,36 @@ func_generate_dlsyms ()
 	func_verbose "creating $output_objdir/$my_dlsyms"
 
 	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
-/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
-/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
+/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */
+/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */
 
 #ifdef __cplusplus
 extern \"C\" {
 #endif
 
-#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
+#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
 #pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
 #endif
 
 /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
+#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE
+/* DATA imports from DLLs on WIN32 can't be const, because runtime
    relocations are performed -- see ld's documentation on pseudo-relocs.  */
 # define LT_DLSYM_CONST
-#elif defined(__osf__)
+#elif defined __osf__
 /* This system does not cope well with relocations in const data.  */
 # define LT_DLSYM_CONST
 #else
 # define LT_DLSYM_CONST const
 #endif
 
+#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)
+
 /* External symbol declarations for the compiler. */\
 "
 
-	if test "$dlself" = yes; then
-	  func_verbose "generating symbol list for \`$output'"
+	if test yes = "$dlself"; then
+	  func_verbose "generating symbol list for '$output'"
 
 	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
 
@@ -3298,7 +4629,7 @@ extern \"C\" {
 	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	  for progfile in $progfiles; do
 	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
-	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
+	    func_verbose "extracting global C symbols from '$func_to_tool_file_result'"
 	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
 	  done
 
@@ -3318,10 +4649,10 @@ extern \"C\" {
 
 	  # Prepare the list of exported symbols
 	  if test -z "$export_symbols"; then
-	    export_symbols="$output_objdir/$outputname.exp"
+	    export_symbols=$output_objdir/$outputname.exp
 	    $opt_dry_run || {
 	      $RM $export_symbols
-	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+	      eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
 	      case $host in
 	      *cygwin* | *mingw* | *cegcc* )
                 eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
@@ -3331,7 +4662,7 @@ extern \"C\" {
 	    }
 	  else
 	    $opt_dry_run || {
-	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      eval "$SED -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
 	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
 	      eval '$MV "$nlist"T "$nlist"'
 	      case $host in
@@ -3345,22 +4676,22 @@ extern \"C\" {
 	fi
 
 	for dlprefile in $dlprefiles; do
-	  func_verbose "extracting global C symbols from \`$dlprefile'"
+	  func_verbose "extracting global C symbols from '$dlprefile'"
 	  func_basename "$dlprefile"
-	  name="$func_basename_result"
+	  name=$func_basename_result
           case $host in
 	    *cygwin* | *mingw* | *cegcc* )
 	      # if an import library, we need to obtain dlname
 	      if func_win32_import_lib_p "$dlprefile"; then
 	        func_tr_sh "$dlprefile"
 	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
-	        dlprefile_dlbasename=""
+	        dlprefile_dlbasename=
 	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
 	          # Use subshell, to avoid clobbering current variable values
 	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
-	          if test -n "$dlprefile_dlname" ; then
+	          if test -n "$dlprefile_dlname"; then
 	            func_basename "$dlprefile_dlname"
-	            dlprefile_dlbasename="$func_basename_result"
+	            dlprefile_dlbasename=$func_basename_result
 	          else
 	            # no lafile. user explicitly requested -dlpreopen <import library>.
 	            $sharedlib_from_linklib_cmd "$dlprefile"
@@ -3368,7 +4699,7 @@ extern \"C\" {
 	          fi
 	        fi
 	        $opt_dry_run || {
-	          if test -n "$dlprefile_dlbasename" ; then
+	          if test -n "$dlprefile_dlbasename"; then
 	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
 	          else
 	            func_warning "Could not compute DLL name from $name"
@@ -3424,6 +4755,11 @@ extern \"C\" {
 	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
 	  fi
 
+	  func_show_eval '$RM "${nlist}I"'
+	  if test -n "$global_symbol_to_import"; then
+	    eval "$global_symbol_to_import"' < "$nlist"S > "$nlist"I'
+	  fi
+
 	  echo >> "$output_objdir/$my_dlsyms" "\
 
 /* The mapping between symbol names and symbols.  */
@@ -3432,11 +4768,30 @@ typedef struct {
   void *address;
 } lt_dlsymlist;
 extern LT_DLSYM_CONST lt_dlsymlist
-lt_${my_prefix}_LTX_preloaded_symbols[];
+lt_${my_prefix}_LTX_preloaded_symbols[];\
+"
+
+	  if test -s "$nlist"I; then
+	    echo >> "$output_objdir/$my_dlsyms" "\
+static void lt_syminit(void)
+{
+  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;
+  for (; symbol->name; ++symbol)
+    {"
+	    $SED 's/.*/      if (STREQ (symbol->name, \"&\")) symbol->address = (void *) \&&;/' < "$nlist"I >> "$output_objdir/$my_dlsyms"
+	    echo >> "$output_objdir/$my_dlsyms" "\
+    }
+}"
+	  fi
+	  echo >> "$output_objdir/$my_dlsyms" "\
 LT_DLSYM_CONST lt_dlsymlist
 lt_${my_prefix}_LTX_preloaded_symbols[] =
-{\
-  { \"$my_originator\", (void *) 0 },"
+{ {\"$my_originator\", (void *) 0},"
+
+	  if test -s "$nlist"I; then
+	    echo >> "$output_objdir/$my_dlsyms" "\
+  {\"@INIT@\", (void *) &lt_syminit},"
+	  fi
 
 	  case $need_lib_prefix in
 	  no)
@@ -3478,9 +4833,7 @@ static const void *lt_preloaded_setup() {
 	  *-*-hpux*)
 	    pic_flag_for_symtable=" $pic_flag"  ;;
 	  *)
-	    if test "X$my_pic_p" != Xno; then
-	      pic_flag_for_symtable=" $pic_flag"
-	    fi
+	    $my_pic_p && pic_flag_for_symtable=" $pic_flag"
 	    ;;
 	  esac
 	  ;;
@@ -3497,10 +4850,10 @@ static const void *lt_preloaded_setup() {
 	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
 
 	# Clean up the generated files.
-	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'
+	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T" "${nlist}I"'
 
 	# Transform the symbol file into the correct name.
-	symfileobj="$output_objdir/${my_outputname}S.$objext"
+	symfileobj=$output_objdir/${my_outputname}S.$objext
 	case $host in
 	*cygwin* | *mingw* | *cegcc* )
 	  if test -f "$output_objdir/$my_outputname.def"; then
@@ -3518,7 +4871,7 @@ static const void *lt_preloaded_setup() {
 	esac
 	;;
       *)
-	func_fatal_error "unknown suffix for \`$my_dlsyms'"
+	func_fatal_error "unknown suffix for '$my_dlsyms'"
 	;;
       esac
     else
@@ -3532,6 +4885,32 @@ static const void *lt_preloaded_setup() {
     fi
 }
 
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $debug_cmd
+
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $debug_cmd
+
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
 # func_win32_libid arg
 # return the library type of file 'arg'
 #
@@ -3541,8 +4920,9 @@ static const void *lt_preloaded_setup() {
 # Despite the name, also deal with 64 bit binaries.
 func_win32_libid ()
 {
-  $opt_debug
-  win32_libid_type="unknown"
+  $debug_cmd
+
+  win32_libid_type=unknown
   win32_fileres=`file -L $1 2>/dev/null`
   case $win32_fileres in
   *ar\ archive\ import\ library*) # definitely import
@@ -3552,16 +4932,29 @@ func_win32_libid ()
     # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
     if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
        $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
-      func_to_tool_file "$1" func_convert_file_msys_to_w32
-      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
-	$SED -n -e '
+      case $nm_interface in
+      "MS dumpbin")
+	if func_cygming_ms_implib_p "$1" ||
+	   func_cygming_gnu_implib_p "$1"
+	then
+	  win32_nmres=import
+	else
+	  win32_nmres=
+	fi
+	;;
+      *)
+	func_to_tool_file "$1" func_convert_file_msys_to_w32
+	win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
+	  $SED -n -e '
 	    1,100{
 		/ I /{
-		    s,.*,import,
+		    s|.*|import|
 		    p
 		    q
 		}
 	    }'`
+	;;
+      esac
       case $win32_nmres in
       import*)  win32_libid_type="x86 archive import";;
       *)        win32_libid_type="x86 archive static";;
@@ -3593,7 +4986,8 @@ func_win32_libid ()
 #    $sharedlib_from_linklib_result
 func_cygming_dll_for_implib ()
 {
-  $opt_debug
+  $debug_cmd
+
   sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
 }
 
@@ -3610,7 +5004,8 @@ func_cygming_dll_for_implib ()
 # specified import library.
 func_cygming_dll_for_implib_fallback_core ()
 {
-  $opt_debug
+  $debug_cmd
+
   match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
   $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
     $SED '/^Contents of section '"$match_literal"':/{
@@ -3646,8 +5041,8 @@ func_cygming_dll_for_implib_fallback_core ()
       /./p' |
     # we now have a list, one entry per line, of the stringified
     # contents of the appropriate section of all members of the
-    # archive which possess that section. Heuristic: eliminate
-    # all those which have a first or second character that is
+    # archive that possess that section. Heuristic: eliminate
+    # all those that have a first or second character that is
     # a '.' (that is, objdump's representation of an unprintable
     # character.) This should work for all archives with less than
     # 0x302f exports -- but will fail for DLLs whose name actually
@@ -3658,30 +5053,6 @@ func_cygming_dll_for_implib_fallback_core ()
     $SED -e '/^\./d;/^.\./d;q'
 }
 
-# func_cygming_gnu_implib_p ARG
-# This predicate returns with zero status (TRUE) if
-# ARG is a GNU/binutils-style import library. Returns
-# with nonzero status (FALSE) otherwise.
-func_cygming_gnu_implib_p ()
-{
-  $opt_debug
-  func_to_tool_file "$1" func_convert_file_msys_to_w32
-  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
-  test -n "$func_cygming_gnu_implib_tmp"
-}
-
-# func_cygming_ms_implib_p ARG
-# This predicate returns with zero status (TRUE) if
-# ARG is an MS-style import library. Returns
-# with nonzero status (FALSE) otherwise.
-func_cygming_ms_implib_p ()
-{
-  $opt_debug
-  func_to_tool_file "$1" func_convert_file_msys_to_w32
-  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
-  test -n "$func_cygming_ms_implib_tmp"
-}
-
 # func_cygming_dll_for_implib_fallback ARG
 # Platform-specific function to extract the
 # name of the DLL associated with the specified
@@ -3695,16 +5066,17 @@ func_cygming_ms_implib_p ()
 #    $sharedlib_from_linklib_result
 func_cygming_dll_for_implib_fallback ()
 {
-  $opt_debug
-  if func_cygming_gnu_implib_p "$1" ; then
+  $debug_cmd
+
+  if func_cygming_gnu_implib_p "$1"; then
     # binutils import library
     sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
-  elif func_cygming_ms_implib_p "$1" ; then
+  elif func_cygming_ms_implib_p "$1"; then
     # ms-generated import library
     sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
   else
     # unknown
-    sharedlib_from_linklib_result=""
+    sharedlib_from_linklib_result=
   fi
 }
 
@@ -3712,10 +5084,11 @@ func_cygming_dll_for_implib_fallback ()
 # func_extract_an_archive dir oldlib
 func_extract_an_archive ()
 {
-    $opt_debug
-    f_ex_an_ar_dir="$1"; shift
-    f_ex_an_ar_oldlib="$1"
-    if test "$lock_old_archive_extraction" = yes; then
+    $debug_cmd
+
+    f_ex_an_ar_dir=$1; shift
+    f_ex_an_ar_oldlib=$1
+    if test yes = "$lock_old_archive_extraction"; then
       lockfile=$f_ex_an_ar_oldlib.lock
       until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
 	func_echo "Waiting for $lockfile to be removed"
@@ -3724,7 +5097,7 @@ func_extract_an_archive ()
     fi
     func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
 		   'stat=$?; rm -f "$lockfile"; exit $stat'
-    if test "$lock_old_archive_extraction" = yes; then
+    if test yes = "$lock_old_archive_extraction"; then
       $opt_dry_run || rm -f "$lockfile"
     fi
     if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
@@ -3738,22 +5111,23 @@ func_extract_an_archive ()
 # func_extract_archives gentop oldlib ...
 func_extract_archives ()
 {
-    $opt_debug
-    my_gentop="$1"; shift
+    $debug_cmd
+
+    my_gentop=$1; shift
     my_oldlibs=${1+"$@"}
-    my_oldobjs=""
-    my_xlib=""
-    my_xabs=""
-    my_xdir=""
+    my_oldobjs=
+    my_xlib=
+    my_xabs=
+    my_xdir=
 
     for my_xlib in $my_oldlibs; do
       # Extract the objects.
       case $my_xlib in
-	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
+	[\\/]* | [A-Za-z]:[\\/]*) my_xabs=$my_xlib ;;
 	*) my_xabs=`pwd`"/$my_xlib" ;;
       esac
       func_basename "$my_xlib"
-      my_xlib="$func_basename_result"
+      my_xlib=$func_basename_result
       my_xlib_u=$my_xlib
       while :; do
         case " $extracted_archives " in
@@ -3765,7 +5139,7 @@ func_extract_archives ()
 	esac
       done
       extracted_archives="$extracted_archives $my_xlib_u"
-      my_xdir="$my_gentop/$my_xlib_u"
+      my_xdir=$my_gentop/$my_xlib_u
 
       func_mkdir_p "$my_xdir"
 
@@ -3778,22 +5152,23 @@ func_extract_archives ()
 	  cd $my_xdir || exit $?
 	  darwin_archive=$my_xabs
 	  darwin_curdir=`pwd`
-	  darwin_base_archive=`basename "$darwin_archive"`
+	  func_basename "$darwin_archive"
+	  darwin_base_archive=$func_basename_result
 	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
 	  if test -n "$darwin_arches"; then
 	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
 	    darwin_arch=
 	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
-	    for darwin_arch in  $darwin_arches ; do
-	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
-	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
-	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
-	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
+	    for darwin_arch in  $darwin_arches; do
+	      func_mkdir_p "unfat-$$/$darwin_base_archive-$darwin_arch"
+	      $LIPO -thin $darwin_arch -output "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive" "$darwin_archive"
+	      cd "unfat-$$/$darwin_base_archive-$darwin_arch"
+	      func_extract_an_archive "`pwd`" "$darwin_base_archive"
 	      cd "$darwin_curdir"
-	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
+	      $RM "unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive"
 	    done # $darwin_arches
             ## Okay now we've a bunch of thin objects, gotta fatten them up :)
-	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
+	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$sed_basename" | sort -u`
 	    darwin_file=
 	    darwin_files=
 	    for darwin_file in $darwin_filelist; do
@@ -3815,7 +5190,7 @@ func_extract_archives ()
       my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
     done
 
-    func_extract_archives_result="$my_oldobjs"
+    func_extract_archives_result=$my_oldobjs
 }
 
 
@@ -3830,7 +5205,7 @@ func_extract_archives ()
 #
 # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
 # variable will take.  If 'yes', then the emitted script
-# will assume that the directory in which it is stored is
+# will assume that the directory where it is stored is
 # the $objdir directory.  This is a cygwin/mingw-specific
 # behavior.
 func_emit_wrapper ()
@@ -3841,7 +5216,7 @@ func_emit_wrapper ()
 #! $SHELL
 
 # $output - temporary wrapper script for $objdir/$outputname
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+# Generated by $PROGRAM (GNU $PACKAGE) $VERSION
 #
 # The $output program cannot be directly executed until all the libtool
 # libraries that it depends on are installed.
@@ -3898,9 +5273,9 @@ _LTECHO_EOF'
 
 # Very basic option parsing. These options are (a) specific to
 # the libtool wrapper, (b) are identical between the wrapper
-# /script/ and the wrapper /executable/ which is used only on
+# /script/ and the wrapper /executable/ that is used only on
 # windows platforms, and (c) all begin with the string "--lt-"
-# (application programs are unlikely to have options which match
+# (application programs are unlikely to have options that match
 # this pattern).
 #
 # There are only two supported options: --lt-debug and
@@ -3933,7 +5308,7 @@ func_parse_lt_options ()
 
   # Print the debug banner immediately:
   if test -n \"\$lt_option_debug\"; then
-    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
+    echo \"$outputname:$output:\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\" 1>&2
   fi
 }
 
@@ -3944,7 +5319,7 @@ func_lt_dump_args ()
   lt_dump_args_N=1;
   for lt_arg
   do
-    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
+    \$ECHO \"$outputname:$output:\$LINENO: newargv[\$lt_dump_args_N]: \$lt_arg\"
     lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
   done
 }
@@ -3958,7 +5333,7 @@ func_exec_program_core ()
   *-*-mingw | *-*-os2* | *-cegcc*)
     $ECHO "\
       if test -n \"\$lt_option_debug\"; then
-        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
+        \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2
         func_lt_dump_args \${1+\"\$@\"} 1>&2
       fi
       exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
@@ -3968,7 +5343,7 @@ func_exec_program_core ()
   *)
     $ECHO "\
       if test -n \"\$lt_option_debug\"; then
-        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
+        \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir/\$program\" 1>&2
         func_lt_dump_args \${1+\"\$@\"} 1>&2
       fi
       exec \"\$progdir/\$program\" \${1+\"\$@\"}
@@ -4043,13 +5418,13 @@ func_exec_program ()
   test -n \"\$absdir\" && thisdir=\"\$absdir\"
 "
 
-	if test "$fast_install" = yes; then
+	if test yes = "$fast_install"; then
 	  $ECHO "\
   program=lt-'$outputname'$exeext
   progdir=\"\$thisdir/$objdir\"
 
   if test ! -f \"\$progdir/\$program\" ||
-     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
+     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | $SED 1q\`; \\
        test \"X\$file\" != \"X\$progdir/\$program\"; }; then
 
     file=\"\$\$-\$program\"
@@ -4066,7 +5441,7 @@ func_exec_program ()
     if test -n \"\$relink_command\"; then
       if relink_command_output=\`eval \$relink_command 2>&1\`; then :
       else
-	$ECHO \"\$relink_command_output\" >&2
+	\$ECHO \"\$relink_command_output\" >&2
 	$RM \"\$progdir/\$file\"
 	exit 1
       fi
@@ -4101,7 +5476,7 @@ func_exec_program ()
 	fi
 
 	# Export our shlibpath_var if we have one.
-	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
 	  $ECHO "\
     # Add our own library path to $shlibpath_var
     $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
@@ -4121,7 +5496,7 @@ func_exec_program ()
     fi
   else
     # The program doesn't exist.
-    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"\$0: error: '\$progdir/\$program' does not exist\" 1>&2
     \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
     \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
     exit 1
@@ -4140,7 +5515,7 @@ func_emit_cwrapperexe_src ()
 	cat <<EOF
 
 /* $cwrappersource - temporary wrapper executable for $objdir/$outputname
-   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+   Generated by $PROGRAM (GNU $PACKAGE) $VERSION
 
    The $output program cannot be directly executed until all the libtool
    libraries that it depends on are installed.
@@ -4175,47 +5550,45 @@ EOF
 #include <fcntl.h>
 #include <sys/stat.h>
 
+#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)
+
 /* declarations of non-ANSI functions */
-#if defined(__MINGW32__)
+#if defined __MINGW32__
 # ifdef __STRICT_ANSI__
 int _putenv (const char *);
 # endif
-#elif defined(__CYGWIN__)
+#elif defined __CYGWIN__
 # ifdef __STRICT_ANSI__
 char *realpath (const char *, char *);
 int putenv (char *);
 int setenv (const char *, const char *, int);
 # endif
-/* #elif defined (other platforms) ... */
+/* #elif defined other_platform || defined ... */
 #endif
 
 /* portability defines, excluding path handling macros */
-#if defined(_MSC_VER)
+#if defined _MSC_VER
 # define setmode _setmode
 # define stat    _stat
 # define chmod   _chmod
 # define getcwd  _getcwd
 # define putenv  _putenv
 # define S_IXUSR _S_IEXEC
-# ifndef _INTPTR_T_DEFINED
-#  define _INTPTR_T_DEFINED
-#  define intptr_t int
-# endif
-#elif defined(__MINGW32__)
+#elif defined __MINGW32__
 # define setmode _setmode
 # define stat    _stat
 # define chmod   _chmod
 # define getcwd  _getcwd
 # define putenv  _putenv
-#elif defined(__CYGWIN__)
+#elif defined __CYGWIN__
 # define HAVE_SETENV
 # define FOPEN_WB "wb"
-/* #elif defined (other platforms) ... */
+/* #elif defined other platforms ... */
 #endif
 
-#if defined(PATH_MAX)
+#if defined PATH_MAX
 # define LT_PATHMAX PATH_MAX
-#elif defined(MAXPATHLEN)
+#elif defined MAXPATHLEN
 # define LT_PATHMAX MAXPATHLEN
 #else
 # define LT_PATHMAX 1024
@@ -4234,8 +5607,8 @@ int setenv (const char *, const char *, int);
 # define PATH_SEPARATOR ':'
 #endif
 
-#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
-  defined (__OS2__)
+#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \
+  defined __OS2__
 # define HAVE_DOS_BASED_FILE_SYSTEM
 # define FOPEN_WB "wb"
 # ifndef DIR_SEPARATOR_2
@@ -4268,10 +5641,10 @@ int setenv (const char *, const char *, int);
 
 #define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
 #define XFREE(stale) do { \
-  if (stale) { free ((void *) stale); stale = 0; } \
+  if (stale) { free (stale); stale = 0; } \
 } while (0)
 
-#if defined(LT_DEBUGWRAPPER)
+#if defined LT_DEBUGWRAPPER
 static int lt_debug = 1;
 #else
 static int lt_debug = 0;
@@ -4300,11 +5673,16 @@ void lt_dump_script (FILE *f);
 EOF
 
 	    cat <<EOF
-volatile const char * MAGIC_EXE = "$magic_exe";
+#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)
+# define externally_visible volatile
+#else
+# define externally_visible __attribute__((externally_visible)) volatile
+#endif
+externally_visible const char * MAGIC_EXE = "$magic_exe";
 const char * LIB_PATH_VARNAME = "$shlibpath_var";
 EOF
 
-	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
+	    if test yes = "$shlibpath_overrides_runpath" && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
               func_to_host_path "$temp_rpath"
 	      cat <<EOF
 const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
@@ -4328,7 +5706,7 @@ const char * EXE_PATH_VALUE   = "";
 EOF
 	    fi
 
-	    if test "$fast_install" = yes; then
+	    if test yes = "$fast_install"; then
 	      cat <<EOF
 const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
 EOF
@@ -4357,12 +5735,12 @@ main (int argc, char *argv[])
   char *actual_cwrapper_name;
   char *target_name;
   char *lt_argv_zero;
-  intptr_t rval = 127;
+  int rval = 127;
 
   int i;
 
   program_name = (char *) xstrdup (base_name (argv[0]));
-  newargz = XMALLOC (char *, argc + 1);
+  newargz = XMALLOC (char *, (size_t) argc + 1);
 
   /* very simple arg parsing; don't want to rely on getopt
    * also, copy all non cwrapper options to newargz, except
@@ -4371,10 +5749,10 @@ main (int argc, char *argv[])
   newargc=0;
   for (i = 1; i < argc; i++)
     {
-      if (strcmp (argv[i], dumpscript_opt) == 0)
+      if (STREQ (argv[i], dumpscript_opt))
 	{
 EOF
-	    case "$host" in
+	    case $host in
 	      *mingw* | *cygwin* )
 		# make stdout use "unix" line endings
 		echo "          setmode(1,_O_BINARY);"
@@ -4385,12 +5763,12 @@ EOF
 	  lt_dump_script (stdout);
 	  return 0;
 	}
-      if (strcmp (argv[i], debug_opt) == 0)
+      if (STREQ (argv[i], debug_opt))
 	{
           lt_debug = 1;
           continue;
 	}
-      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
+      if (STREQ (argv[i], ltwrapper_option_prefix))
         {
           /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
              namespace, but it is not one of the ones we know about and
@@ -4413,7 +5791,7 @@ EOF
 EOF
 	    cat <<EOF
   /* The GNU banner must be the first non-error debug message */
-  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE) $VERSION\n");
 EOF
 	    cat <<"EOF"
   lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
@@ -4524,7 +5902,7 @@ EOF
 		cat <<"EOF"
   /* execv doesn't actually work on mingw as expected on unix */
   newargz = prepare_spawn (newargz);
-  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
   if (rval == -1)
     {
       /* failed to start process */
@@ -4569,7 +5947,7 @@ base_name (const char *name)
 {
   const char *base;
 
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+#if defined HAVE_DOS_BASED_FILE_SYSTEM
   /* Skip over the disk name in MSDOS pathnames. */
   if (isalpha ((unsigned char) name[0]) && name[1] == ':')
     name += 2;
@@ -4628,7 +6006,7 @@ find_executable (const char *wrapper)
   const char *p_next;
   /* static buffer for getcwd */
   char tmp[LT_PATHMAX + 1];
-  int tmp_len;
+  size_t tmp_len;
   char *concat_name;
 
   lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
@@ -4638,7 +6016,7 @@ find_executable (const char *wrapper)
     return NULL;
 
   /* Absolute path? */
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+#if defined HAVE_DOS_BASED_FILE_SYSTEM
   if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
     {
       concat_name = xstrdup (wrapper);
@@ -4656,7 +6034,7 @@ find_executable (const char *wrapper)
 	    return concat_name;
 	  XFREE (concat_name);
 	}
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+#if defined HAVE_DOS_BASED_FILE_SYSTEM
     }
 #endif
 
@@ -4679,7 +6057,7 @@ find_executable (const char *wrapper)
 	      for (q = p; *q; q++)
 		if (IS_PATH_SEPARATOR (*q))
 		  break;
-	      p_len = q - p;
+	      p_len = (size_t) (q - p);
 	      p_next = (*q == '\0' ? q : q + 1);
 	      if (p_len == 0)
 		{
@@ -4798,7 +6176,7 @@ strendzap (char *str, const char *pat)
   if (patlen <= len)
     {
       str += len - patlen;
-      if (strcmp (str, pat) == 0)
+      if (STREQ (str, pat))
 	*str = '\0';
     }
   return str;
@@ -4863,7 +6241,7 @@ lt_setenv (const char *name, const char *value)
     char *str = xstrdup (value);
     setenv (name, str, 1);
 #else
-    int len = strlen (name) + 1 + strlen (value) + 1;
+    size_t len = strlen (name) + 1 + strlen (value) + 1;
     char *str = XMALLOC (char, len);
     sprintf (str, "%s=%s", name, value);
     if (putenv (str) != EXIT_SUCCESS)
@@ -4880,8 +6258,8 @@ lt_extend_str (const char *orig_value, const char *add, int to_end)
   char *new_value;
   if (orig_value && *orig_value)
     {
-      int orig_value_len = strlen (orig_value);
-      int add_len = strlen (add);
+      size_t orig_value_len = strlen (orig_value);
+      size_t add_len = strlen (add);
       new_value = XMALLOC (char, add_len + orig_value_len + 1);
       if (to_end)
         {
@@ -4912,10 +6290,10 @@ lt_update_exe_path (const char *name, const char *value)
     {
       char *new_value = lt_extend_str (getenv (name), value, 0);
       /* some systems can't cope with a ':'-terminated path #' */
-      int len = strlen (new_value);
-      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
+      size_t len = strlen (new_value);
+      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
         {
-          new_value[len-1] = '\0';
+          new_value[--len] = '\0';
         }
       lt_setenv (name, new_value);
       XFREE (new_value);
@@ -5082,27 +6460,47 @@ EOF
 # True if ARG is an import lib, as indicated by $file_magic_cmd
 func_win32_import_lib_p ()
 {
-    $opt_debug
+    $debug_cmd
+
     case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
     *import*) : ;;
     *) false ;;
     esac
 }
 
+# func_suncc_cstd_abi
+# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!
+# Several compiler flags select an ABI that is incompatible with the
+# Cstd library. Avoid specifying it if any are in CXXFLAGS.
+func_suncc_cstd_abi ()
+{
+    $debug_cmd
+
+    case " $compile_command " in
+    *" -compat=g "*|*\ -std=c++[0-9][0-9]\ *|*" -library=stdcxx4 "*|*" -library=stlport4 "*)
+      suncc_use_cstd_abi=no
+      ;;
+    *)
+      suncc_use_cstd_abi=yes
+      ;;
+    esac
+}
+
 # func_mode_link arg...
 func_mode_link ()
 {
-    $opt_debug
+    $debug_cmd
+
     case $host in
     *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
       # It is impossible to link a dll without this setting, and
       # we shouldn't force the makefile maintainer to figure out
-      # which system we are compiling for in order to pass an extra
+      # what system we are compiling for in order to pass an extra
       # flag for every libtool invocation.
       # allow_undefined=no
 
       # FIXME: Unfortunately, there are problems with the above when trying
-      # to make a dll which has undefined symbols, in which case not
+      # to make a dll that has undefined symbols, in which case not
       # even a static library is built.  For now, we need to specify
       # -no-undefined on the libtool link line when we can be certain
       # that all symbols are satisfied, otherwise we get a static library.
@@ -5146,10 +6544,11 @@ func_mode_link ()
     module=no
     no_install=no
     objs=
+    os2dllname=
     non_pic_objects=
     precious_files_regex=
     prefer_static_libs=no
-    preload=no
+    preload=false
     prev=
     prevarg=
     release=
@@ -5161,7 +6560,7 @@ func_mode_link ()
     vinfo=
     vinfo_number=no
     weak_libs=
-    single_module="${wl}-single_module"
+    single_module=$wl-single_module
     func_infer_tag $base_compile
 
     # We need to know -static, to get the right output filenames.
@@ -5169,15 +6568,15 @@ func_mode_link ()
     do
       case $arg in
       -shared)
-	test "$build_libtool_libs" != yes && \
-	  func_fatal_configuration "can not build a shared library"
+	test yes != "$build_libtool_libs" \
+	  && func_fatal_configuration "cannot build a shared library"
 	build_old_libs=no
 	break
 	;;
       -all-static | -static | -static-libtool-libs)
 	case $arg in
 	-all-static)
-	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
+	  if test yes = "$build_libtool_libs" && test -z "$link_static_flag"; then
 	    func_warning "complete static linking is impossible in this configuration"
 	  fi
 	  if test -n "$link_static_flag"; then
@@ -5210,7 +6609,7 @@ func_mode_link ()
 
     # Go through the arguments, transforming them on the way.
     while test "$#" -gt 0; do
-      arg="$1"
+      arg=$1
       shift
       func_quote_for_eval "$arg"
       qarg=$func_quote_for_eval_unquoted_result
@@ -5227,21 +6626,21 @@ func_mode_link ()
 
 	case $prev in
 	bindir)
-	  bindir="$arg"
+	  bindir=$arg
 	  prev=
 	  continue
 	  ;;
 	dlfiles|dlprefiles)
-	  if test "$preload" = no; then
+	  $preload || {
 	    # Add the symbol object into the linking commands.
 	    func_append compile_command " @SYMFILE@"
 	    func_append finalize_command " @SYMFILE@"
-	    preload=yes
-	  fi
+	    preload=:
+	  }
 	  case $arg in
 	  *.la | *.lo) ;;  # We handle these cases below.
 	  force)
-	    if test "$dlself" = no; then
+	    if test no = "$dlself"; then
 	      dlself=needless
 	      export_dynamic=yes
 	    fi
@@ -5249,9 +6648,9 @@ func_mode_link ()
 	    continue
 	    ;;
 	  self)
-	    if test "$prev" = dlprefiles; then
+	    if test dlprefiles = "$prev"; then
 	      dlself=yes
-	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
+	    elif test dlfiles = "$prev" && test yes != "$dlopen_self"; then
 	      dlself=yes
 	    else
 	      dlself=needless
@@ -5261,7 +6660,7 @@ func_mode_link ()
 	    continue
 	    ;;
 	  *)
-	    if test "$prev" = dlfiles; then
+	    if test dlfiles = "$prev"; then
 	      func_append dlfiles " $arg"
 	    else
 	      func_append dlprefiles " $arg"
@@ -5272,14 +6671,14 @@ func_mode_link ()
 	  esac
 	  ;;
 	expsyms)
-	  export_symbols="$arg"
+	  export_symbols=$arg
 	  test -f "$arg" \
-	    || func_fatal_error "symbol file \`$arg' does not exist"
+	    || func_fatal_error "symbol file '$arg' does not exist"
 	  prev=
 	  continue
 	  ;;
 	expsyms_regex)
-	  export_symbols_regex="$arg"
+	  export_symbols_regex=$arg
 	  prev=
 	  continue
 	  ;;
@@ -5297,7 +6696,13 @@ func_mode_link ()
 	  continue
 	  ;;
 	inst_prefix)
-	  inst_prefix_dir="$arg"
+	  inst_prefix_dir=$arg
+	  prev=
+	  continue
+	  ;;
+	mllvm)
+	  # Clang does not use LLVM to link, so we can simply discard any
+	  # '-mllvm $arg' options when doing the link step.
 	  prev=
 	  continue
 	  ;;
@@ -5321,21 +6726,21 @@ func_mode_link ()
 
 		if test -z "$pic_object" ||
 		   test -z "$non_pic_object" ||
-		   test "$pic_object" = none &&
-		   test "$non_pic_object" = none; then
-		  func_fatal_error "cannot find name of object for \`$arg'"
+		   test none = "$pic_object" &&
+		   test none = "$non_pic_object"; then
+		  func_fatal_error "cannot find name of object for '$arg'"
 		fi
 
 		# Extract subdirectory from the argument.
 		func_dirname "$arg" "/" ""
-		xdir="$func_dirname_result"
+		xdir=$func_dirname_result
 
-		if test "$pic_object" != none; then
+		if test none != "$pic_object"; then
 		  # Prepend the subdirectory the object is found in.
-		  pic_object="$xdir$pic_object"
+		  pic_object=$xdir$pic_object
 
-		  if test "$prev" = dlfiles; then
-		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+		  if test dlfiles = "$prev"; then
+		    if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then
 		      func_append dlfiles " $pic_object"
 		      prev=
 		      continue
@@ -5346,7 +6751,7 @@ func_mode_link ()
 		  fi
 
 		  # CHECK ME:  I think I busted this.  -Ossama
-		  if test "$prev" = dlprefiles; then
+		  if test dlprefiles = "$prev"; then
 		    # Preload the old-style object.
 		    func_append dlprefiles " $pic_object"
 		    prev=
@@ -5354,23 +6759,23 @@ func_mode_link ()
 
 		  # A PIC object.
 		  func_append libobjs " $pic_object"
-		  arg="$pic_object"
+		  arg=$pic_object
 		fi
 
 		# Non-PIC object.
-		if test "$non_pic_object" != none; then
+		if test none != "$non_pic_object"; then
 		  # Prepend the subdirectory the object is found in.
-		  non_pic_object="$xdir$non_pic_object"
+		  non_pic_object=$xdir$non_pic_object
 
 		  # A standard non-PIC object
 		  func_append non_pic_objects " $non_pic_object"
-		  if test -z "$pic_object" || test "$pic_object" = none ; then
-		    arg="$non_pic_object"
+		  if test -z "$pic_object" || test none = "$pic_object"; then
+		    arg=$non_pic_object
 		  fi
 		else
 		  # If the PIC object exists, use it instead.
 		  # $xdir was prepended to $pic_object above.
-		  non_pic_object="$pic_object"
+		  non_pic_object=$pic_object
 		  func_append non_pic_objects " $non_pic_object"
 		fi
 	      else
@@ -5378,7 +6783,7 @@ func_mode_link ()
 		if $opt_dry_run; then
 		  # Extract subdirectory from the argument.
 		  func_dirname "$arg" "/" ""
-		  xdir="$func_dirname_result"
+		  xdir=$func_dirname_result
 
 		  func_lo2o "$arg"
 		  pic_object=$xdir$objdir/$func_lo2o_result
@@ -5386,24 +6791,29 @@ func_mode_link ()
 		  func_append libobjs " $pic_object"
 		  func_append non_pic_objects " $non_pic_object"
 	        else
-		  func_fatal_error "\`$arg' is not a valid libtool object"
+		  func_fatal_error "'$arg' is not a valid libtool object"
 		fi
 	      fi
 	    done
 	  else
-	    func_fatal_error "link input file \`$arg' does not exist"
+	    func_fatal_error "link input file '$arg' does not exist"
 	  fi
 	  arg=$save_arg
 	  prev=
 	  continue
 	  ;;
+	os2dllname)
+	  os2dllname=$arg
+	  prev=
+	  continue
+	  ;;
 	precious_regex)
-	  precious_files_regex="$arg"
+	  precious_files_regex=$arg
 	  prev=
 	  continue
 	  ;;
 	release)
-	  release="-$arg"
+	  release=-$arg
 	  prev=
 	  continue
 	  ;;
@@ -5415,7 +6825,7 @@ func_mode_link ()
 	    func_fatal_error "only absolute run-paths are allowed"
 	    ;;
 	  esac
-	  if test "$prev" = rpath; then
+	  if test rpath = "$prev"; then
 	    case "$rpath " in
 	    *" $arg "*) ;;
 	    *) func_append rpath " $arg" ;;
@@ -5430,7 +6840,7 @@ func_mode_link ()
 	  continue
 	  ;;
 	shrext)
-	  shrext_cmds="$arg"
+	  shrext_cmds=$arg
 	  prev=
 	  continue
 	  ;;
@@ -5470,7 +6880,7 @@ func_mode_link ()
 	esac
       fi # test -n "$prev"
 
-      prevarg="$arg"
+      prevarg=$arg
 
       case $arg in
       -all-static)
@@ -5484,7 +6894,7 @@ func_mode_link ()
 
       -allow-undefined)
 	# FIXME: remove this flag sometime in the future.
-	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
+	func_fatal_error "'-allow-undefined' must not be used because it is the default"
 	;;
 
       -avoid-version)
@@ -5516,7 +6926,7 @@ func_mode_link ()
 	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
 	  func_fatal_error "more than one -exported-symbols argument is not allowed"
 	fi
-	if test "X$arg" = "X-export-symbols"; then
+	if test X-export-symbols = "X$arg"; then
 	  prev=expsyms
 	else
 	  prev=expsyms_regex
@@ -5550,9 +6960,9 @@ func_mode_link ()
 	func_stripname "-L" '' "$arg"
 	if test -z "$func_stripname_result"; then
 	  if test "$#" -gt 0; then
-	    func_fatal_error "require no space between \`-L' and \`$1'"
+	    func_fatal_error "require no space between '-L' and '$1'"
 	  else
-	    func_fatal_error "need path for \`-L' option"
+	    func_fatal_error "need path for '-L' option"
 	  fi
 	fi
 	func_resolve_sysroot "$func_stripname_result"
@@ -5563,8 +6973,8 @@ func_mode_link ()
 	*)
 	  absdir=`cd "$dir" && pwd`
 	  test -z "$absdir" && \
-	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
-	  dir="$absdir"
+	    func_fatal_error "cannot determine absolute directory name of '$dir'"
+	  dir=$absdir
 	  ;;
 	esac
 	case "$deplibs " in
@@ -5599,7 +7009,7 @@ func_mode_link ()
 	;;
 
       -l*)
-	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
+	if test X-lc = "X$arg" || test X-lm = "X$arg"; then
 	  case $host in
 	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
 	    # These systems don't actually have a C or math library (as such)
@@ -5607,11 +7017,11 @@ func_mode_link ()
 	    ;;
 	  *-*-os2*)
 	    # These systems don't actually have a C library (as such)
-	    test "X$arg" = "X-lc" && continue
+	    test X-lc = "X$arg" && continue
 	    ;;
-	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)
 	    # Do not include libc due to us having libc/libc_r.
-	    test "X$arg" = "X-lc" && continue
+	    test X-lc = "X$arg" && continue
 	    ;;
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C and math libraries are in the System framework
@@ -5620,16 +7030,16 @@ func_mode_link ()
 	    ;;
 	  *-*-sco3.2v5* | *-*-sco5v6*)
 	    # Causes problems with __ctype
-	    test "X$arg" = "X-lc" && continue
+	    test X-lc = "X$arg" && continue
 	    ;;
 	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
 	    # Compiler inserts libc in the correct place for threads to work
-	    test "X$arg" = "X-lc" && continue
+	    test X-lc = "X$arg" && continue
 	    ;;
 	  esac
-	elif test "X$arg" = "X-lc_r"; then
+	elif test X-lc_r = "X$arg"; then
 	 case $host in
-	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
+	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)
 	   # Do not include libc_r directly, use -pthread flag.
 	   continue
 	   ;;
@@ -5639,6 +7049,11 @@ func_mode_link ()
 	continue
 	;;
 
+      -mllvm)
+	prev=mllvm
+	continue
+	;;
+
       -module)
 	module=yes
 	continue
@@ -5668,7 +7083,7 @@ func_mode_link ()
 	;;
 
       -multi_module)
-	single_module="${wl}-multi_module"
+	single_module=$wl-multi_module
 	continue
 	;;
 
@@ -5682,8 +7097,8 @@ func_mode_link ()
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
 	  # The PATH hackery in wrapper scripts is required on Windows
 	  # and Darwin in order for the loader to find any dlls it needs.
-	  func_warning "\`-no-install' is ignored for $host"
-	  func_warning "assuming \`-no-fast-install' instead"
+	  func_warning "'-no-install' is ignored for $host"
+	  func_warning "assuming '-no-fast-install' instead"
 	  fast_install=no
 	  ;;
 	*) no_install=yes ;;
@@ -5701,6 +7116,11 @@ func_mode_link ()
 	continue
 	;;
 
+      -os2dllname)
+	prev=os2dllname
+	continue
+	;;
+
       -o) prev=output ;;
 
       -precious-files-regex)
@@ -5788,14 +7208,14 @@ func_mode_link ()
 	func_stripname '-Wc,' '' "$arg"
 	args=$func_stripname_result
 	arg=
-	save_ifs="$IFS"; IFS=','
+	save_ifs=$IFS; IFS=,
 	for flag in $args; do
-	  IFS="$save_ifs"
+	  IFS=$save_ifs
           func_quote_for_eval "$flag"
 	  func_append arg " $func_quote_for_eval_result"
 	  func_append compiler_flags " $func_quote_for_eval_result"
 	done
-	IFS="$save_ifs"
+	IFS=$save_ifs
 	func_stripname ' ' '' "$arg"
 	arg=$func_stripname_result
 	;;
@@ -5804,15 +7224,15 @@ func_mode_link ()
 	func_stripname '-Wl,' '' "$arg"
 	args=$func_stripname_result
 	arg=
-	save_ifs="$IFS"; IFS=','
+	save_ifs=$IFS; IFS=,
 	for flag in $args; do
-	  IFS="$save_ifs"
+	  IFS=$save_ifs
           func_quote_for_eval "$flag"
 	  func_append arg " $wl$func_quote_for_eval_result"
 	  func_append compiler_flags " $wl$func_quote_for_eval_result"
 	  func_append linker_flags " $func_quote_for_eval_result"
 	done
-	IFS="$save_ifs"
+	IFS=$save_ifs
 	func_stripname ' ' '' "$arg"
 	arg=$func_stripname_result
 	;;
@@ -5835,7 +7255,7 @@ func_mode_link ()
       # -msg_* for osf cc
       -msg_*)
 	func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
+	arg=$func_quote_for_eval_result
 	;;
 
       # Flags to be passed through unchanged, with rationale:
@@ -5847,25 +7267,49 @@ func_mode_link ()
       # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
       # -F/path              path to uninstalled frameworks, gcc on darwin
       # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # -fstack-protector*   stack protector flags for GCC
       # @file                GCC response files
       # -tp=*                Portland pgcc target processor selection
       # --sysroot=*          for sysroot support
-      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+      # -specs=*             GCC specs files
+      # -stdlib=*            select c++ std lib with clang
+      # -fsanitize=*         Clang/GCC memory and address sanitizer
       -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
       -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
-      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
+      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \
+      -specs=*|-fsanitize=*)
         func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
+	arg=$func_quote_for_eval_result
         func_append compile_command " $arg"
         func_append finalize_command " $arg"
         func_append compiler_flags " $arg"
         continue
         ;;
 
+      -Z*)
+        if test os2 = "`expr $host : '.*\(os2\)'`"; then
+          # OS/2 uses -Zxxx to specify OS/2-specific options
+	  compiler_flags="$compiler_flags $arg"
+	  func_append compile_command " $arg"
+	  func_append finalize_command " $arg"
+	  case $arg in
+	  -Zlinker | -Zstack)
+	    prev=xcompiler
+	    ;;
+	  esac
+	  continue
+        else
+	  # Otherwise treat like 'Some other compiler flag' below
+	  func_quote_for_eval "$arg"
+	  arg=$func_quote_for_eval_result
+        fi
+	;;
+
       # Some other compiler flag.
       -* | +*)
         func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
+	arg=$func_quote_for_eval_result
 	;;
 
       *.$objext)
@@ -5886,21 +7330,21 @@ func_mode_link ()
 
 	  if test -z "$pic_object" ||
 	     test -z "$non_pic_object" ||
-	     test "$pic_object" = none &&
-	     test "$non_pic_object" = none; then
-	    func_fatal_error "cannot find name of object for \`$arg'"
+	     test none = "$pic_object" &&
+	     test none = "$non_pic_object"; then
+	    func_fatal_error "cannot find name of object for '$arg'"
 	  fi
 
 	  # Extract subdirectory from the argument.
 	  func_dirname "$arg" "/" ""
-	  xdir="$func_dirname_result"
+	  xdir=$func_dirname_result
 
-	  if test "$pic_object" != none; then
+	  test none = "$pic_object" || {
 	    # Prepend the subdirectory the object is found in.
-	    pic_object="$xdir$pic_object"
+	    pic_object=$xdir$pic_object
 
-	    if test "$prev" = dlfiles; then
-	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
+	    if test dlfiles = "$prev"; then
+	      if test yes = "$build_libtool_libs" && test yes = "$dlopen_support"; then
 		func_append dlfiles " $pic_object"
 		prev=
 		continue
@@ -5911,7 +7355,7 @@ func_mode_link ()
 	    fi
 
 	    # CHECK ME:  I think I busted this.  -Ossama
-	    if test "$prev" = dlprefiles; then
+	    if test dlprefiles = "$prev"; then
 	      # Preload the old-style object.
 	      func_append dlprefiles " $pic_object"
 	      prev=
@@ -5919,23 +7363,23 @@ func_mode_link ()
 
 	    # A PIC object.
 	    func_append libobjs " $pic_object"
-	    arg="$pic_object"
-	  fi
+	    arg=$pic_object
+	  }
 
 	  # Non-PIC object.
-	  if test "$non_pic_object" != none; then
+	  if test none != "$non_pic_object"; then
 	    # Prepend the subdirectory the object is found in.
-	    non_pic_object="$xdir$non_pic_object"
+	    non_pic_object=$xdir$non_pic_object
 
 	    # A standard non-PIC object
 	    func_append non_pic_objects " $non_pic_object"
-	    if test -z "$pic_object" || test "$pic_object" = none ; then
-	      arg="$non_pic_object"
+	    if test -z "$pic_object" || test none = "$pic_object"; then
+	      arg=$non_pic_object
 	    fi
 	  else
 	    # If the PIC object exists, use it instead.
 	    # $xdir was prepended to $pic_object above.
-	    non_pic_object="$pic_object"
+	    non_pic_object=$pic_object
 	    func_append non_pic_objects " $non_pic_object"
 	  fi
 	else
@@ -5943,7 +7387,7 @@ func_mode_link ()
 	  if $opt_dry_run; then
 	    # Extract subdirectory from the argument.
 	    func_dirname "$arg" "/" ""
-	    xdir="$func_dirname_result"
+	    xdir=$func_dirname_result
 
 	    func_lo2o "$arg"
 	    pic_object=$xdir$objdir/$func_lo2o_result
@@ -5951,7 +7395,7 @@ func_mode_link ()
 	    func_append libobjs " $pic_object"
 	    func_append non_pic_objects " $non_pic_object"
 	  else
-	    func_fatal_error "\`$arg' is not a valid libtool object"
+	    func_fatal_error "'$arg' is not a valid libtool object"
 	  fi
 	fi
 	;;
@@ -5967,11 +7411,11 @@ func_mode_link ()
 	# A libtool-controlled library.
 
 	func_resolve_sysroot "$arg"
-	if test "$prev" = dlfiles; then
+	if test dlfiles = "$prev"; then
 	  # This library was specified with -dlopen.
 	  func_append dlfiles " $func_resolve_sysroot_result"
 	  prev=
-	elif test "$prev" = dlprefiles; then
+	elif test dlprefiles = "$prev"; then
 	  # The library was specified with -dlpreopen.
 	  func_append dlprefiles " $func_resolve_sysroot_result"
 	  prev=
@@ -5986,7 +7430,7 @@ func_mode_link ()
 	# Unknown arguments in both finalize_command and compile_command need
 	# to be aesthetically quoted because they are evaled later.
 	func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
+	arg=$func_quote_for_eval_result
 	;;
       esac # arg
 
@@ -5998,9 +7442,9 @@ func_mode_link ()
     done # argument parsing loop
 
     test -n "$prev" && \
-      func_fatal_help "the \`$prevarg' option requires an argument"
+      func_fatal_help "the '$prevarg' option requires an argument"
 
-    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
+    if test yes = "$export_dynamic" && test -n "$export_dynamic_flag_spec"; then
       eval arg=\"$export_dynamic_flag_spec\"
       func_append compile_command " $arg"
       func_append finalize_command " $arg"
@@ -6009,20 +7453,23 @@ func_mode_link ()
     oldlibs=
     # calculate the name of the file, without its directory
     func_basename "$output"
-    outputname="$func_basename_result"
-    libobjs_save="$libobjs"
+    outputname=$func_basename_result
+    libobjs_save=$libobjs
 
     if test -n "$shlibpath_var"; then
       # get the directories listed in $shlibpath_var
-      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
+      eval shlib_search_path=\`\$ECHO \"\$$shlibpath_var\" \| \$SED \'s/:/ /g\'\`
     else
       shlib_search_path=
     fi
     eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
     eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
 
+    # Definition is injected by LT_CONFIG during libtool generation.
+    func_munge_path_list sys_lib_dlsearch_path "$LT_SYS_LIBRARY_PATH"
+
     func_dirname "$output" "/" ""
-    output_objdir="$func_dirname_result$objdir"
+    output_objdir=$func_dirname_result$objdir
     func_to_tool_file "$output_objdir/"
     tool_output_objdir=$func_to_tool_file_result
     # Create the object directory.
@@ -6045,7 +7492,7 @@ func_mode_link ()
     # Find all interdependent deplibs by searching for libraries
     # that are linked more than once (e.g. -la -lb -la)
     for deplib in $deplibs; do
-      if $opt_preserve_dup_deps ; then
+      if $opt_preserve_dup_deps; then
 	case "$libs " in
 	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	esac
@@ -6053,7 +7500,7 @@ func_mode_link ()
       func_append libs " $deplib"
     done
 
-    if test "$linkmode" = lib; then
+    if test lib = "$linkmode"; then
       libs="$predeps $libs $compiler_lib_search_path $postdeps"
 
       # Compute libraries that are listed more than once in $predeps
@@ -6085,7 +7532,7 @@ func_mode_link ()
 	  case $file in
 	  *.la) ;;
 	  *)
-	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
+	    func_fatal_help "libraries can '-dlopen' only libtool libraries: $file"
 	    ;;
 	  esac
 	done
@@ -6093,7 +7540,7 @@ func_mode_link ()
     prog)
 	compile_deplibs=
 	finalize_deplibs=
-	alldeplibs=no
+	alldeplibs=false
 	newdlfiles=
 	newdlprefiles=
 	passes="conv scan dlopen dlpreopen link"
@@ -6105,32 +7552,32 @@ func_mode_link ()
     for pass in $passes; do
       # The preopen pass in lib mode reverses $deplibs; put it back here
       # so that -L comes before libs that need it for instance...
-      if test "$linkmode,$pass" = "lib,link"; then
+      if test lib,link = "$linkmode,$pass"; then
 	## FIXME: Find the place where the list is rebuilt in the wrong
 	##        order, and fix it there properly
         tmp_deplibs=
 	for deplib in $deplibs; do
 	  tmp_deplibs="$deplib $tmp_deplibs"
 	done
-	deplibs="$tmp_deplibs"
+	deplibs=$tmp_deplibs
       fi
 
-      if test "$linkmode,$pass" = "lib,link" ||
-	 test "$linkmode,$pass" = "prog,scan"; then
-	libs="$deplibs"
+      if test lib,link = "$linkmode,$pass" ||
+	 test prog,scan = "$linkmode,$pass"; then
+	libs=$deplibs
 	deplibs=
       fi
-      if test "$linkmode" = prog; then
+      if test prog = "$linkmode"; then
 	case $pass in
-	dlopen) libs="$dlfiles" ;;
-	dlpreopen) libs="$dlprefiles" ;;
+	dlopen) libs=$dlfiles ;;
+	dlpreopen) libs=$dlprefiles ;;
 	link)
 	  libs="$deplibs %DEPLIBS%"
 	  test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs"
 	  ;;
 	esac
       fi
-      if test "$linkmode,$pass" = "lib,dlpreopen"; then
+      if test lib,dlpreopen = "$linkmode,$pass"; then
 	# Collect and forward deplibs of preopened libtool libs
 	for lib in $dlprefiles; do
 	  # Ignore non-libtool-libs
@@ -6151,26 +7598,26 @@ func_mode_link ()
 	    esac
 	  done
 	done
-	libs="$dlprefiles"
+	libs=$dlprefiles
       fi
-      if test "$pass" = dlopen; then
+      if test dlopen = "$pass"; then
 	# Collect dlpreopened libraries
-	save_deplibs="$deplibs"
+	save_deplibs=$deplibs
 	deplibs=
       fi
 
       for deplib in $libs; do
 	lib=
-	found=no
+	found=false
 	case $deplib in
 	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
         |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
-	  if test "$linkmode,$pass" = "prog,link"; then
+	  if test prog,link = "$linkmode,$pass"; then
 	    compile_deplibs="$deplib $compile_deplibs"
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
 	    func_append compiler_flags " $deplib"
-	    if test "$linkmode" = lib ; then
+	    if test lib = "$linkmode"; then
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
 		    * ) func_append new_inherited_linker_flags " $deplib" ;;
@@ -6180,13 +7627,13 @@ func_mode_link ()
 	  continue
 	  ;;
 	-l*)
-	  if test "$linkmode" != lib && test "$linkmode" != prog; then
-	    func_warning "\`-l' is ignored for archives/objects"
+	  if test lib != "$linkmode" && test prog != "$linkmode"; then
+	    func_warning "'-l' is ignored for archives/objects"
 	    continue
 	  fi
 	  func_stripname '-l' '' "$deplib"
 	  name=$func_stripname_result
-	  if test "$linkmode" = lib; then
+	  if test lib = "$linkmode"; then
 	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
 	  else
 	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
@@ -6194,31 +7641,22 @@ func_mode_link ()
 	  for searchdir in $searchdirs; do
 	    for search_ext in .la $std_shrext .so .a; do
 	      # Search the libtool library
-	      lib="$searchdir/lib${name}${search_ext}"
+	      lib=$searchdir/lib$name$search_ext
 	      if test -f "$lib"; then
-		if test "$search_ext" = ".la"; then
-		  found=yes
+		if test .la = "$search_ext"; then
+		  found=:
 		else
-		  found=no
+		  found=false
 		fi
 		break 2
 	      fi
 	    done
 	  done
-	  if test "$found" != yes; then
-	    # deplib doesn't seem to be a libtool library
-	    if test "$linkmode,$pass" = "prog,link"; then
-	      compile_deplibs="$deplib $compile_deplibs"
-	      finalize_deplibs="$deplib $finalize_deplibs"
-	    else
-	      deplibs="$deplib $deplibs"
-	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
-	    fi
-	    continue
-	  else # deplib is a libtool library
+	  if $found; then
+	    # deplib is a libtool library
 	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
 	    # We need to do some special things here, and not later.
-	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	    if test yes = "$allow_libtool_libs_with_static_runtimes"; then
 	      case " $predeps $postdeps " in
 	      *" $deplib "*)
 		if func_lalib_p "$lib"; then
@@ -6226,19 +7664,19 @@ func_mode_link ()
 		  old_library=
 		  func_source "$lib"
 		  for l in $old_library $library_names; do
-		    ll="$l"
+		    ll=$l
 		  done
-		  if test "X$ll" = "X$old_library" ; then # only static version available
-		    found=no
+		  if test "X$ll" = "X$old_library"; then # only static version available
+		    found=false
 		    func_dirname "$lib" "" "."
-		    ladir="$func_dirname_result"
+		    ladir=$func_dirname_result
 		    lib=$ladir/$old_library
-		    if test "$linkmode,$pass" = "prog,link"; then
+		    if test prog,link = "$linkmode,$pass"; then
 		      compile_deplibs="$deplib $compile_deplibs"
 		      finalize_deplibs="$deplib $finalize_deplibs"
 		    else
 		      deplibs="$deplib $deplibs"
-		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
+		      test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs"
 		    fi
 		    continue
 		  fi
@@ -6247,15 +7685,25 @@ func_mode_link ()
 	      *) ;;
 	      esac
 	    fi
+	  else
+	    # deplib doesn't seem to be a libtool library
+	    if test prog,link = "$linkmode,$pass"; then
+	      compile_deplibs="$deplib $compile_deplibs"
+	      finalize_deplibs="$deplib $finalize_deplibs"
+	    else
+	      deplibs="$deplib $deplibs"
+	      test lib = "$linkmode" && newdependency_libs="$deplib $newdependency_libs"
+	    fi
+	    continue
 	  fi
 	  ;; # -l
 	*.ltframework)
-	  if test "$linkmode,$pass" = "prog,link"; then
+	  if test prog,link = "$linkmode,$pass"; then
 	    compile_deplibs="$deplib $compile_deplibs"
 	    finalize_deplibs="$deplib $finalize_deplibs"
 	  else
 	    deplibs="$deplib $deplibs"
-	    if test "$linkmode" = lib ; then
+	    if test lib = "$linkmode"; then
 		case "$new_inherited_linker_flags " in
 		    *" $deplib "*) ;;
 		    * ) func_append new_inherited_linker_flags " $deplib" ;;
@@ -6268,18 +7716,18 @@ func_mode_link ()
 	  case $linkmode in
 	  lib)
 	    deplibs="$deplib $deplibs"
-	    test "$pass" = conv && continue
+	    test conv = "$pass" && continue
 	    newdependency_libs="$deplib $newdependency_libs"
 	    func_stripname '-L' '' "$deplib"
 	    func_resolve_sysroot "$func_stripname_result"
 	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  prog)
-	    if test "$pass" = conv; then
+	    if test conv = "$pass"; then
 	      deplibs="$deplib $deplibs"
 	      continue
 	    fi
-	    if test "$pass" = scan; then
+	    if test scan = "$pass"; then
 	      deplibs="$deplib $deplibs"
 	    else
 	      compile_deplibs="$deplib $compile_deplibs"
@@ -6290,13 +7738,13 @@ func_mode_link ()
 	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  *)
-	    func_warning "\`-L' is ignored for archives/objects"
+	    func_warning "'-L' is ignored for archives/objects"
 	    ;;
 	  esac # linkmode
 	  continue
 	  ;; # -L
 	-R*)
-	  if test "$pass" = link; then
+	  if test link = "$pass"; then
 	    func_stripname '-R' '' "$deplib"
 	    func_resolve_sysroot "$func_stripname_result"
 	    dir=$func_resolve_sysroot_result
@@ -6314,7 +7762,7 @@ func_mode_link ()
 	  lib=$func_resolve_sysroot_result
 	  ;;
 	*.$libext)
-	  if test "$pass" = conv; then
+	  if test conv = "$pass"; then
 	    deplibs="$deplib $deplibs"
 	    continue
 	  fi
@@ -6325,21 +7773,26 @@ func_mode_link ()
 	    case " $dlpreconveniencelibs " in
 	    *" $deplib "*) ;;
 	    *)
-	      valid_a_lib=no
+	      valid_a_lib=false
 	      case $deplibs_check_method in
 		match_pattern*)
 		  set dummy $deplibs_check_method; shift
 		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
 		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
 		    | $EGREP "$match_pattern_regex" > /dev/null; then
-		    valid_a_lib=yes
+		    valid_a_lib=:
 		  fi
 		;;
 		pass_all)
-		  valid_a_lib=yes
+		  valid_a_lib=:
 		;;
 	      esac
-	      if test "$valid_a_lib" != yes; then
+	      if $valid_a_lib; then
+		echo
+		$ECHO "*** Warning: Linking the shared library $output against the"
+		$ECHO "*** static library $deplib is not portable!"
+		deplibs="$deplib $deplibs"
+	      else
 		echo
 		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
 		echo "*** I have the capability to make that library automatically link in when"
@@ -6347,18 +7800,13 @@ func_mode_link ()
 		echo "*** shared version of the library, which you do not appear to have"
 		echo "*** because the file extensions .$libext of this argument makes me believe"
 		echo "*** that it is just a static archive that I should not use here."
-	      else
-		echo
-		$ECHO "*** Warning: Linking the shared library $output against the"
-		$ECHO "*** static library $deplib is not portable!"
-		deplibs="$deplib $deplibs"
 	      fi
 	      ;;
 	    esac
 	    continue
 	    ;;
 	  prog)
-	    if test "$pass" != link; then
+	    if test link != "$pass"; then
 	      deplibs="$deplib $deplibs"
 	    else
 	      compile_deplibs="$deplib $compile_deplibs"
@@ -6369,10 +7817,10 @@ func_mode_link ()
 	  esac # linkmode
 	  ;; # *.$libext
 	*.lo | *.$objext)
-	  if test "$pass" = conv; then
+	  if test conv = "$pass"; then
 	    deplibs="$deplib $deplibs"
-	  elif test "$linkmode" = prog; then
-	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
+	  elif test prog = "$linkmode"; then
+	    if test dlpreopen = "$pass" || test yes != "$dlopen_support" || test no = "$build_libtool_libs"; then
 	      # If there is no dlopen support or we're linking statically,
 	      # we need to preload.
 	      func_append newdlprefiles " $deplib"
@@ -6385,22 +7833,20 @@ func_mode_link ()
 	  continue
 	  ;;
 	%DEPLIBS%)
-	  alldeplibs=yes
+	  alldeplibs=:
 	  continue
 	  ;;
 	esac # case $deplib
 
-	if test "$found" = yes || test -f "$lib"; then :
-	else
-	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
-	fi
+	$found || test -f "$lib" \
+	  || func_fatal_error "cannot find the library '$lib' or unhandled argument '$deplib'"
 
 	# Check to see that this really is a libtool archive.
 	func_lalib_unsafe_p "$lib" \
-	  || func_fatal_error "\`$lib' is not a valid libtool archive"
+	  || func_fatal_error "'$lib' is not a valid libtool archive"
 
 	func_dirname "$lib" "" "."
-	ladir="$func_dirname_result"
+	ladir=$func_dirname_result
 
 	dlname=
 	dlopen=
@@ -6430,19 +7876,19 @@ func_mode_link ()
 	  done
 	fi
 	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	if test "$linkmode,$pass" = "lib,link" ||
-	   test "$linkmode,$pass" = "prog,scan" ||
-	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
+	if test lib,link = "$linkmode,$pass" ||
+	   test prog,scan = "$linkmode,$pass" ||
+	   { test prog != "$linkmode" && test lib != "$linkmode"; }; then
 	  test -n "$dlopen" && func_append dlfiles " $dlopen"
 	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
 	fi
 
-	if test "$pass" = conv; then
+	if test conv = "$pass"; then
 	  # Only check for convenience libraries
 	  deplibs="$lib $deplibs"
 	  if test -z "$libdir"; then
 	    if test -z "$old_library"; then
-	      func_fatal_error "cannot find name of link library for \`$lib'"
+	      func_fatal_error "cannot find name of link library for '$lib'"
 	    fi
 	    # It is a libtool convenience library, so add in its objects.
 	    func_append convenience " $ladir/$objdir/$old_library"
@@ -6450,15 +7896,15 @@ func_mode_link ()
 	    tmp_libs=
 	    for deplib in $dependency_libs; do
 	      deplibs="$deplib $deplibs"
-	      if $opt_preserve_dup_deps ; then
+	      if $opt_preserve_dup_deps; then
 		case "$tmp_libs " in
 		*" $deplib "*) func_append specialdeplibs " $deplib" ;;
 		esac
 	      fi
 	      func_append tmp_libs " $deplib"
 	    done
-	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
-	    func_fatal_error "\`$lib' is not a convenience library"
+	  elif test prog != "$linkmode" && test lib != "$linkmode"; then
+	    func_fatal_error "'$lib' is not a convenience library"
 	  fi
 	  continue
 	fi # $pass = conv
@@ -6467,26 +7913,26 @@ func_mode_link ()
 	# Get the name of the library we link against.
 	linklib=
 	if test -n "$old_library" &&
-	   { test "$prefer_static_libs" = yes ||
-	     test "$prefer_static_libs,$installed" = "built,no"; }; then
+	   { test yes = "$prefer_static_libs" ||
+	     test built,no = "$prefer_static_libs,$installed"; }; then
 	  linklib=$old_library
 	else
 	  for l in $old_library $library_names; do
-	    linklib="$l"
+	    linklib=$l
 	  done
 	fi
 	if test -z "$linklib"; then
-	  func_fatal_error "cannot find name of link library for \`$lib'"
+	  func_fatal_error "cannot find name of link library for '$lib'"
 	fi
 
 	# This library was specified with -dlopen.
-	if test "$pass" = dlopen; then
-	  if test -z "$libdir"; then
-	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
-	  fi
+	if test dlopen = "$pass"; then
+	  test -z "$libdir" \
+	    && func_fatal_error "cannot -dlopen a convenience library: '$lib'"
 	  if test -z "$dlname" ||
-	     test "$dlopen_support" != yes ||
-	     test "$build_libtool_libs" = no; then
+	     test yes != "$dlopen_support" ||
+	     test no = "$build_libtool_libs"
+	  then
 	    # If there is no dlname, no dlopen support or we're linking
 	    # statically, we need to preload.  We also need to preload any
 	    # dependent libraries so libltdl's deplib preloader doesn't
@@ -6500,40 +7946,40 @@ func_mode_link ()
 
 	# We need an absolute path.
 	case $ladir in
-	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
+	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir=$ladir ;;
 	*)
 	  abs_ladir=`cd "$ladir" && pwd`
 	  if test -z "$abs_ladir"; then
-	    func_warning "cannot determine absolute directory name of \`$ladir'"
+	    func_warning "cannot determine absolute directory name of '$ladir'"
 	    func_warning "passing it literally to the linker, although it might fail"
-	    abs_ladir="$ladir"
+	    abs_ladir=$ladir
 	  fi
 	  ;;
 	esac
 	func_basename "$lib"
-	laname="$func_basename_result"
+	laname=$func_basename_result
 
 	# Find the relevant object directory and library name.
-	if test "X$installed" = Xyes; then
+	if test yes = "$installed"; then
 	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
-	    func_warning "library \`$lib' was moved."
-	    dir="$ladir"
-	    absdir="$abs_ladir"
-	    libdir="$abs_ladir"
+	    func_warning "library '$lib' was moved."
+	    dir=$ladir
+	    absdir=$abs_ladir
+	    libdir=$abs_ladir
 	  else
-	    dir="$lt_sysroot$libdir"
-	    absdir="$lt_sysroot$libdir"
+	    dir=$lt_sysroot$libdir
+	    absdir=$lt_sysroot$libdir
 	  fi
-	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
+	  test yes = "$hardcode_automatic" && avoidtemprpath=yes
 	else
 	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
-	    dir="$ladir"
-	    absdir="$abs_ladir"
+	    dir=$ladir
+	    absdir=$abs_ladir
 	    # Remove this search path later
 	    func_append notinst_path " $abs_ladir"
 	  else
-	    dir="$ladir/$objdir"
-	    absdir="$abs_ladir/$objdir"
+	    dir=$ladir/$objdir
+	    absdir=$abs_ladir/$objdir
 	    # Remove this search path later
 	    func_append notinst_path " $abs_ladir"
 	  fi
@@ -6542,11 +7988,11 @@ func_mode_link ()
 	name=$func_stripname_result
 
 	# This library was specified with -dlpreopen.
-	if test "$pass" = dlpreopen; then
-	  if test -z "$libdir" && test "$linkmode" = prog; then
-	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
+	if test dlpreopen = "$pass"; then
+	  if test -z "$libdir" && test prog = "$linkmode"; then
+	    func_fatal_error "only libraries may -dlpreopen a convenience library: '$lib'"
 	  fi
-	  case "$host" in
+	  case $host in
 	    # special handling for platforms with PE-DLLs.
 	    *cygwin* | *mingw* | *cegcc* )
 	      # Linker will automatically link against shared library if both
@@ -6590,9 +8036,9 @@ func_mode_link ()
 
 	if test -z "$libdir"; then
 	  # Link the convenience library
-	  if test "$linkmode" = lib; then
+	  if test lib = "$linkmode"; then
 	    deplibs="$dir/$old_library $deplibs"
-	  elif test "$linkmode,$pass" = "prog,link"; then
+	  elif test prog,link = "$linkmode,$pass"; then
 	    compile_deplibs="$dir/$old_library $compile_deplibs"
 	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
 	  else
@@ -6602,14 +8048,14 @@ func_mode_link ()
 	fi
 
 
-	if test "$linkmode" = prog && test "$pass" != link; then
+	if test prog = "$linkmode" && test link != "$pass"; then
 	  func_append newlib_search_path " $ladir"
 	  deplibs="$lib $deplibs"
 
-	  linkalldeplibs=no
-	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
-	     test "$build_libtool_libs" = no; then
-	    linkalldeplibs=yes
+	  linkalldeplibs=false
+	  if test no != "$link_all_deplibs" || test -z "$library_names" ||
+	     test no = "$build_libtool_libs"; then
+	    linkalldeplibs=:
 	  fi
 
 	  tmp_libs=
@@ -6621,14 +8067,14 @@ func_mode_link ()
 		 ;;
 	    esac
 	    # Need to link against all dependency_libs?
-	    if test "$linkalldeplibs" = yes; then
+	    if $linkalldeplibs; then
 	      deplibs="$deplib $deplibs"
 	    else
 	      # Need to hardcode shared library paths
 	      # or/and link against static libraries
 	      newdependency_libs="$deplib $newdependency_libs"
 	    fi
-	    if $opt_preserve_dup_deps ; then
+	    if $opt_preserve_dup_deps; then
 	      case "$tmp_libs " in
 	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
@@ -6638,15 +8084,15 @@ func_mode_link ()
 	  continue
 	fi # $linkmode = prog...
 
-	if test "$linkmode,$pass" = "prog,link"; then
+	if test prog,link = "$linkmode,$pass"; then
 	  if test -n "$library_names" &&
-	     { { test "$prefer_static_libs" = no ||
-	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
+	     { { test no = "$prefer_static_libs" ||
+	         test built,yes = "$prefer_static_libs,$installed"; } ||
 	       test -z "$old_library"; }; then
 	    # We need to hardcode the library path
-	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
+	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath"; then
 	      # Make sure the rpath contains only unique directories.
-	      case "$temp_rpath:" in
+	      case $temp_rpath: in
 	      *"$absdir:"*) ;;
 	      *) func_append temp_rpath "$absdir:" ;;
 	      esac
@@ -6675,9 +8121,9 @@ func_mode_link ()
 	    esac
 	  fi # $linkmode,$pass = prog,link...
 
-	  if test "$alldeplibs" = yes &&
-	     { test "$deplibs_check_method" = pass_all ||
-	       { test "$build_libtool_libs" = yes &&
+	  if $alldeplibs &&
+	     { test pass_all = "$deplibs_check_method" ||
+	       { test yes = "$build_libtool_libs" &&
 		 test -n "$library_names"; }; }; then
 	    # We only need to search for static libraries
 	    continue
@@ -6686,19 +8132,19 @@ func_mode_link ()
 
 	link_static=no # Whether the deplib will be linked statically
 	use_static_libs=$prefer_static_libs
-	if test "$use_static_libs" = built && test "$installed" = yes; then
+	if test built = "$use_static_libs" && test yes = "$installed"; then
 	  use_static_libs=no
 	fi
 	if test -n "$library_names" &&
-	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
+	   { test no = "$use_static_libs" || test -z "$old_library"; }; then
 	  case $host in
-	  *cygwin* | *mingw* | *cegcc*)
+	  *cygwin* | *mingw* | *cegcc* | *os2*)
 	      # No point in relinking DLLs because paths are not encoded
 	      func_append notinst_deplibs " $lib"
 	      need_relink=no
 	    ;;
 	  *)
-	    if test "$installed" = no; then
+	    if test no = "$installed"; then
 	      func_append notinst_deplibs " $lib"
 	      need_relink=yes
 	    fi
@@ -6708,24 +8154,24 @@ func_mode_link ()
 
 	  # Warn about portability, can't link against -module's on some
 	  # systems (darwin).  Don't bleat about dlopened modules though!
-	  dlopenmodule=""
+	  dlopenmodule=
 	  for dlpremoduletest in $dlprefiles; do
 	    if test "X$dlpremoduletest" = "X$lib"; then
-	      dlopenmodule="$dlpremoduletest"
+	      dlopenmodule=$dlpremoduletest
 	      break
 	    fi
 	  done
-	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
+	  if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then
 	    echo
-	    if test "$linkmode" = prog; then
+	    if test prog = "$linkmode"; then
 	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
 	    else
 	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
 	    fi
 	    $ECHO "*** $linklib is not portable!"
 	  fi
-	  if test "$linkmode" = lib &&
-	     test "$hardcode_into_libs" = yes; then
+	  if test lib = "$linkmode" &&
+	     test yes = "$hardcode_into_libs"; then
 	    # Hardcode the library path.
 	    # Skip directories that are in the system default run-time
 	    # search path.
@@ -6753,43 +8199,43 @@ func_mode_link ()
 	    # figure out the soname
 	    set dummy $library_names
 	    shift
-	    realname="$1"
+	    realname=$1
 	    shift
 	    libname=`eval "\\$ECHO \"$libname_spec\""`
 	    # use dlname if we got it. it's perfectly good, no?
 	    if test -n "$dlname"; then
-	      soname="$dlname"
+	      soname=$dlname
 	    elif test -n "$soname_spec"; then
 	      # bleh windows
 	      case $host in
-	      *cygwin* | mingw* | *cegcc*)
+	      *cygwin* | mingw* | *cegcc* | *os2*)
 	        func_arith $current - $age
 		major=$func_arith_result
-		versuffix="-$major"
+		versuffix=-$major
 		;;
 	      esac
 	      eval soname=\"$soname_spec\"
 	    else
-	      soname="$realname"
+	      soname=$realname
 	    fi
 
 	    # Make a new name for the extract_expsyms_cmds to use
-	    soroot="$soname"
+	    soroot=$soname
 	    func_basename "$soroot"
-	    soname="$func_basename_result"
+	    soname=$func_basename_result
 	    func_stripname 'lib' '.dll' "$soname"
 	    newlib=libimp-$func_stripname_result.a
 
 	    # If the library has no export list, then create one now
 	    if test -f "$output_objdir/$soname-def"; then :
 	    else
-	      func_verbose "extracting exported symbol list from \`$soname'"
+	      func_verbose "extracting exported symbol list from '$soname'"
 	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
 	    fi
 
 	    # Create $newlib
 	    if test -f "$output_objdir/$newlib"; then :; else
-	      func_verbose "generating import library for \`$soname'"
+	      func_verbose "generating import library for '$soname'"
 	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
 	    fi
 	    # make sure the library variables are pointing to the new library
@@ -6797,58 +8243,58 @@ func_mode_link ()
 	    linklib=$newlib
 	  fi # test -n "$old_archive_from_expsyms_cmds"
 
-	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
+	  if test prog = "$linkmode" || test relink != "$opt_mode"; then
 	    add_shlibpath=
 	    add_dir=
 	    add=
 	    lib_linked=yes
 	    case $hardcode_action in
 	    immediate | unsupported)
-	      if test "$hardcode_direct" = no; then
-		add="$dir/$linklib"
+	      if test no = "$hardcode_direct"; then
+		add=$dir/$linklib
 		case $host in
-		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
-		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
+		  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;
+		  *-*-sysv4*uw2*) add_dir=-L$dir ;;
 		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
-		    *-*-unixware7*) add_dir="-L$dir" ;;
+		    *-*-unixware7*) add_dir=-L$dir ;;
 		  *-*-darwin* )
-		    # if the lib is a (non-dlopened) module then we can not
+		    # if the lib is a (non-dlopened) module then we cannot
 		    # link against it, someone is ignoring the earlier warnings
 		    if /usr/bin/file -L $add 2> /dev/null |
-			 $GREP ": [^:]* bundle" >/dev/null ; then
+			 $GREP ": [^:]* bundle" >/dev/null; then
 		      if test "X$dlopenmodule" != "X$lib"; then
 			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
-			if test -z "$old_library" ; then
+			if test -z "$old_library"; then
 			  echo
 			  echo "*** And there doesn't seem to be a static archive available"
 			  echo "*** The link will probably fail, sorry"
 			else
-			  add="$dir/$old_library"
+			  add=$dir/$old_library
 			fi
 		      elif test -n "$old_library"; then
-			add="$dir/$old_library"
+			add=$dir/$old_library
 		      fi
 		    fi
 		esac
-	      elif test "$hardcode_minus_L" = no; then
+	      elif test no = "$hardcode_minus_L"; then
 		case $host in
-		*-*-sunos*) add_shlibpath="$dir" ;;
+		*-*-sunos*) add_shlibpath=$dir ;;
 		esac
-		add_dir="-L$dir"
-		add="-l$name"
-	      elif test "$hardcode_shlibpath_var" = no; then
-		add_shlibpath="$dir"
-		add="-l$name"
+		add_dir=-L$dir
+		add=-l$name
+	      elif test no = "$hardcode_shlibpath_var"; then
+		add_shlibpath=$dir
+		add=-l$name
 	      else
 		lib_linked=no
 	      fi
 	      ;;
 	    relink)
-	      if test "$hardcode_direct" = yes &&
-	         test "$hardcode_direct_absolute" = no; then
-		add="$dir/$linklib"
-	      elif test "$hardcode_minus_L" = yes; then
-		add_dir="-L$absdir"
+	      if test yes = "$hardcode_direct" &&
+	         test no = "$hardcode_direct_absolute"; then
+		add=$dir/$linklib
+	      elif test yes = "$hardcode_minus_L"; then
+		add_dir=-L$absdir
 		# Try looking first in the location we're being installed to.
 		if test -n "$inst_prefix_dir"; then
 		  case $libdir in
@@ -6857,10 +8303,10 @@ func_mode_link ()
 		      ;;
 		  esac
 		fi
-		add="-l$name"
-	      elif test "$hardcode_shlibpath_var" = yes; then
-		add_shlibpath="$dir"
-		add="-l$name"
+		add=-l$name
+	      elif test yes = "$hardcode_shlibpath_var"; then
+		add_shlibpath=$dir
+		add=-l$name
 	      else
 		lib_linked=no
 	      fi
@@ -6868,7 +8314,7 @@ func_mode_link ()
 	    *) lib_linked=no ;;
 	    esac
 
-	    if test "$lib_linked" != yes; then
+	    if test yes != "$lib_linked"; then
 	      func_fatal_configuration "unsupported hardcode properties"
 	    fi
 
@@ -6878,15 +8324,15 @@ func_mode_link ()
 	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
 	      esac
 	    fi
-	    if test "$linkmode" = prog; then
+	    if test prog = "$linkmode"; then
 	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
 	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
 	    else
 	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
 	      test -n "$add" && deplibs="$add $deplibs"
-	      if test "$hardcode_direct" != yes &&
-		 test "$hardcode_minus_L" != yes &&
-		 test "$hardcode_shlibpath_var" = yes; then
+	      if test yes != "$hardcode_direct" &&
+		 test yes != "$hardcode_minus_L" &&
+		 test yes = "$hardcode_shlibpath_var"; then
 		case :$finalize_shlibpath: in
 		*":$libdir:"*) ;;
 		*) func_append finalize_shlibpath "$libdir:" ;;
@@ -6895,33 +8341,33 @@ func_mode_link ()
 	    fi
 	  fi
 
-	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
+	  if test prog = "$linkmode" || test relink = "$opt_mode"; then
 	    add_shlibpath=
 	    add_dir=
 	    add=
 	    # Finalize command for both is simple: just hardcode it.
-	    if test "$hardcode_direct" = yes &&
-	       test "$hardcode_direct_absolute" = no; then
-	      add="$libdir/$linklib"
-	    elif test "$hardcode_minus_L" = yes; then
-	      add_dir="-L$libdir"
-	      add="-l$name"
-	    elif test "$hardcode_shlibpath_var" = yes; then
+	    if test yes = "$hardcode_direct" &&
+	       test no = "$hardcode_direct_absolute"; then
+	      add=$libdir/$linklib
+	    elif test yes = "$hardcode_minus_L"; then
+	      add_dir=-L$libdir
+	      add=-l$name
+	    elif test yes = "$hardcode_shlibpath_var"; then
 	      case :$finalize_shlibpath: in
 	      *":$libdir:"*) ;;
 	      *) func_append finalize_shlibpath "$libdir:" ;;
 	      esac
-	      add="-l$name"
-	    elif test "$hardcode_automatic" = yes; then
+	      add=-l$name
+	    elif test yes = "$hardcode_automatic"; then
 	      if test -n "$inst_prefix_dir" &&
-		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
-		add="$inst_prefix_dir$libdir/$linklib"
+		 test -f "$inst_prefix_dir$libdir/$linklib"; then
+		add=$inst_prefix_dir$libdir/$linklib
 	      else
-		add="$libdir/$linklib"
+		add=$libdir/$linklib
 	      fi
 	    else
 	      # We cannot seem to hardcode it, guess we'll fake it.
-	      add_dir="-L$libdir"
+	      add_dir=-L$libdir
 	      # Try looking first in the location we're being installed to.
 	      if test -n "$inst_prefix_dir"; then
 		case $libdir in
@@ -6930,10 +8376,10 @@ func_mode_link ()
 		    ;;
 		esac
 	      fi
-	      add="-l$name"
+	      add=-l$name
 	    fi
 
-	    if test "$linkmode" = prog; then
+	    if test prog = "$linkmode"; then
 	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
 	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
 	    else
@@ -6941,43 +8387,43 @@ func_mode_link ()
 	      test -n "$add" && deplibs="$add $deplibs"
 	    fi
 	  fi
-	elif test "$linkmode" = prog; then
+	elif test prog = "$linkmode"; then
 	  # Here we assume that one of hardcode_direct or hardcode_minus_L
 	  # is not unsupported.  This is valid on all known static and
 	  # shared platforms.
-	  if test "$hardcode_direct" != unsupported; then
-	    test -n "$old_library" && linklib="$old_library"
+	  if test unsupported != "$hardcode_direct"; then
+	    test -n "$old_library" && linklib=$old_library
 	    compile_deplibs="$dir/$linklib $compile_deplibs"
 	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
 	  else
 	    compile_deplibs="-l$name -L$dir $compile_deplibs"
 	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
 	  fi
-	elif test "$build_libtool_libs" = yes; then
+	elif test yes = "$build_libtool_libs"; then
 	  # Not a shared library
-	  if test "$deplibs_check_method" != pass_all; then
+	  if test pass_all != "$deplibs_check_method"; then
 	    # We're trying link a shared library against a static one
 	    # but the system doesn't support it.
 
 	    # Just print a warning and add the library to dependency_libs so
 	    # that the program can be linked against the static library.
 	    echo
-	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
+	    $ECHO "*** Warning: This system cannot link to static lib archive $lib."
 	    echo "*** I have the capability to make that library automatically link in when"
 	    echo "*** you link to this library.  But I can only do this if you have a"
 	    echo "*** shared version of the library, which you do not appear to have."
-	    if test "$module" = yes; then
+	    if test yes = "$module"; then
 	      echo "*** But as you try to build a module library, libtool will still create "
 	      echo "*** a static module, that should work as long as the dlopening application"
 	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
 	      if test -z "$global_symbol_pipe"; then
 		echo
 		echo "*** However, this would only work if libtool was able to extract symbol"
-		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+		echo "*** lists from a program, using 'nm' or equivalent, but libtool could"
 		echo "*** not find such a program.  So, this module is probably useless."
-		echo "*** \`nm' from GNU binutils and a full rebuild may help."
+		echo "*** 'nm' from GNU binutils and a full rebuild may help."
 	      fi
-	      if test "$build_old_libs" = no; then
+	      if test no = "$build_old_libs"; then
 		build_libtool_libs=module
 		build_old_libs=yes
 	      else
@@ -6990,11 +8436,11 @@ func_mode_link ()
 	  fi
 	fi # link shared/static library?
 
-	if test "$linkmode" = lib; then
+	if test lib = "$linkmode"; then
 	  if test -n "$dependency_libs" &&
-	     { test "$hardcode_into_libs" != yes ||
-	       test "$build_old_libs" = yes ||
-	       test "$link_static" = yes; }; then
+	     { test yes != "$hardcode_into_libs" ||
+	       test yes = "$build_old_libs" ||
+	       test yes = "$link_static"; }; then
 	    # Extract -R from dependency_libs
 	    temp_deplibs=
 	    for libdir in $dependency_libs; do
@@ -7008,12 +8454,12 @@ func_mode_link ()
 	      *) func_append temp_deplibs " $libdir";;
 	      esac
 	    done
-	    dependency_libs="$temp_deplibs"
+	    dependency_libs=$temp_deplibs
 	  fi
 
 	  func_append newlib_search_path " $absdir"
 	  # Link against this library
-	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
+	  test no = "$link_static" && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
 	  # ... and its dependency_libs
 	  tmp_libs=
 	  for deplib in $dependency_libs; do
@@ -7023,7 +8469,7 @@ func_mode_link ()
                    func_resolve_sysroot "$func_stripname_result";;
               *) func_resolve_sysroot "$deplib" ;;
             esac
-	    if $opt_preserve_dup_deps ; then
+	    if $opt_preserve_dup_deps; then
 	      case "$tmp_libs " in
 	      *" $func_resolve_sysroot_result "*)
                 func_append specialdeplibs " $func_resolve_sysroot_result" ;;
@@ -7032,12 +8478,12 @@ func_mode_link ()
 	    func_append tmp_libs " $func_resolve_sysroot_result"
 	  done
 
-	  if test "$link_all_deplibs" != no; then
+	  if test no != "$link_all_deplibs"; then
 	    # Add the search paths of all dependency libraries
 	    for deplib in $dependency_libs; do
 	      path=
 	      case $deplib in
-	      -L*) path="$deplib" ;;
+	      -L*) path=$deplib ;;
 	      *.la)
 	        func_resolve_sysroot "$deplib"
 	        deplib=$func_resolve_sysroot_result
@@ -7045,12 +8491,12 @@ func_mode_link ()
 		dir=$func_dirname_result
 		# We need an absolute path.
 		case $dir in
-		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
+		[\\/]* | [A-Za-z]:[\\/]*) absdir=$dir ;;
 		*)
 		  absdir=`cd "$dir" && pwd`
 		  if test -z "$absdir"; then
-		    func_warning "cannot determine absolute directory name of \`$dir'"
-		    absdir="$dir"
+		    func_warning "cannot determine absolute directory name of '$dir'"
+		    absdir=$dir
 		  fi
 		  ;;
 		esac
@@ -7058,35 +8504,35 @@ func_mode_link ()
 		case $host in
 		*-*-darwin*)
 		  depdepl=
-		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
-		  if test -n "$deplibrary_names" ; then
-		    for tmp in $deplibrary_names ; do
+		  eval deplibrary_names=`$SED -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
+		  if test -n "$deplibrary_names"; then
+		    for tmp in $deplibrary_names; do
 		      depdepl=$tmp
 		    done
-		    if test -f "$absdir/$objdir/$depdepl" ; then
-		      depdepl="$absdir/$objdir/$depdepl"
-		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
+		    if test -f "$absdir/$objdir/$depdepl"; then
+		      depdepl=$absdir/$objdir/$depdepl
+		      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
                       if test -z "$darwin_install_name"; then
-                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
+                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
                       fi
-		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
-		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
+		      func_append compiler_flags " $wl-dylib_file $wl$darwin_install_name:$depdepl"
+		      func_append linker_flags " -dylib_file $darwin_install_name:$depdepl"
 		      path=
 		    fi
 		  fi
 		  ;;
 		*)
-		  path="-L$absdir/$objdir"
+		  path=-L$absdir/$objdir
 		  ;;
 		esac
 		else
-		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
+		  eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
 		  test -z "$libdir" && \
-		    func_fatal_error "\`$deplib' is not a valid libtool archive"
+		    func_fatal_error "'$deplib' is not a valid libtool archive"
 		  test "$absdir" != "$libdir" && \
-		    func_warning "\`$deplib' seems to be moved"
+		    func_warning "'$deplib' seems to be moved"
 
-		  path="-L$absdir"
+		  path=-L$absdir
 		fi
 		;;
 	      esac
@@ -7098,23 +8544,23 @@ func_mode_link ()
 	  fi # link_all_deplibs != no
 	fi # linkmode = lib
       done # for deplib in $libs
-      if test "$pass" = link; then
-	if test "$linkmode" = "prog"; then
+      if test link = "$pass"; then
+	if test prog = "$linkmode"; then
 	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
 	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
 	else
 	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
 	fi
       fi
-      dependency_libs="$newdependency_libs"
-      if test "$pass" = dlpreopen; then
+      dependency_libs=$newdependency_libs
+      if test dlpreopen = "$pass"; then
 	# Link the dlpreopened libraries before other libraries
 	for deplib in $save_deplibs; do
 	  deplibs="$deplib $deplibs"
 	done
       fi
-      if test "$pass" != dlopen; then
-	if test "$pass" != conv; then
+      if test dlopen != "$pass"; then
+	test conv = "$pass" || {
 	  # Make sure lib_search_path contains only unique directories.
 	  lib_search_path=
 	  for dir in $newlib_search_path; do
@@ -7124,12 +8570,12 @@ func_mode_link ()
 	    esac
 	  done
 	  newlib_search_path=
-	fi
+	}
 
-	if test "$linkmode,$pass" != "prog,link"; then
-	  vars="deplibs"
-	else
+	if test prog,link = "$linkmode,$pass"; then
 	  vars="compile_deplibs finalize_deplibs"
+	else
+	  vars=deplibs
 	fi
 	for var in $vars dependency_libs; do
 	  # Add libraries to $var in reverse order
@@ -7187,62 +8633,93 @@ func_mode_link ()
 	  eval $var=\"$tmp_libs\"
 	done # for var
       fi
+
+      # Add Sun CC postdeps if required:
+      test CXX = "$tagname" && {
+        case $host_os in
+        linux*)
+          case `$CC -V 2>&1 | sed 5q` in
+          *Sun\ C*) # Sun C++ 5.9
+            func_suncc_cstd_abi
+
+            if test no != "$suncc_use_cstd_abi"; then
+              func_append postdeps ' -library=Cstd -library=Crun'
+            fi
+            ;;
+          esac
+          ;;
+
+        solaris*)
+          func_cc_basename "$CC"
+          case $func_cc_basename_result in
+          CC* | sunCC*)
+            func_suncc_cstd_abi
+
+            if test no != "$suncc_use_cstd_abi"; then
+              func_append postdeps ' -library=Cstd -library=Crun'
+            fi
+            ;;
+          esac
+          ;;
+        esac
+      }
+
       # Last step: remove runtime libs from dependency_libs
       # (they stay in deplibs)
       tmp_libs=
-      for i in $dependency_libs ; do
+      for i in $dependency_libs; do
 	case " $predeps $postdeps $compiler_lib_search_path " in
 	*" $i "*)
-	  i=""
+	  i=
 	  ;;
 	esac
-	if test -n "$i" ; then
+	if test -n "$i"; then
 	  func_append tmp_libs " $i"
 	fi
       done
       dependency_libs=$tmp_libs
     done # for pass
-    if test "$linkmode" = prog; then
-      dlfiles="$newdlfiles"
+    if test prog = "$linkmode"; then
+      dlfiles=$newdlfiles
     fi
-    if test "$linkmode" = prog || test "$linkmode" = lib; then
-      dlprefiles="$newdlprefiles"
+    if test prog = "$linkmode" || test lib = "$linkmode"; then
+      dlprefiles=$newdlprefiles
     fi
 
     case $linkmode in
     oldlib)
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
-	func_warning "\`-dlopen' is ignored for archives"
+      if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then
+	func_warning "'-dlopen' is ignored for archives"
       fi
 
       case " $deplibs" in
       *\ -l* | *\ -L*)
-	func_warning "\`-l' and \`-L' are ignored for archives" ;;
+	func_warning "'-l' and '-L' are ignored for archives" ;;
       esac
 
       test -n "$rpath" && \
-	func_warning "\`-rpath' is ignored for archives"
+	func_warning "'-rpath' is ignored for archives"
 
       test -n "$xrpath" && \
-	func_warning "\`-R' is ignored for archives"
+	func_warning "'-R' is ignored for archives"
 
       test -n "$vinfo" && \
-	func_warning "\`-version-info/-version-number' is ignored for archives"
+	func_warning "'-version-info/-version-number' is ignored for archives"
 
       test -n "$release" && \
-	func_warning "\`-release' is ignored for archives"
+	func_warning "'-release' is ignored for archives"
 
       test -n "$export_symbols$export_symbols_regex" && \
-	func_warning "\`-export-symbols' is ignored for archives"
+	func_warning "'-export-symbols' is ignored for archives"
 
       # Now set the variables for building old libraries.
       build_libtool_libs=no
-      oldlibs="$output"
+      oldlibs=$output
       func_append objs "$old_deplibs"
       ;;
 
     lib)
-      # Make sure we only generate libraries of the form `libNAME.la'.
+      # Make sure we only generate libraries of the form 'libNAME.la'.
       case $outputname in
       lib*)
 	func_stripname 'lib' '.la' "$outputname"
@@ -7251,10 +8728,10 @@ func_mode_link ()
 	eval libname=\"$libname_spec\"
 	;;
       *)
-	test "$module" = no && \
-	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
+	test no = "$module" \
+	  && func_fatal_help "libtool library '$output' must begin with 'lib'"
 
-	if test "$need_lib_prefix" != no; then
+	if test no != "$need_lib_prefix"; then
 	  # Add the "lib" prefix for modules if required
 	  func_stripname '' '.la' "$outputname"
 	  name=$func_stripname_result
@@ -7268,8 +8745,8 @@ func_mode_link ()
       esac
 
       if test -n "$objs"; then
-	if test "$deplibs_check_method" != pass_all; then
-	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
+	if test pass_all != "$deplibs_check_method"; then
+	  func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs"
 	else
 	  echo
 	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
@@ -7278,21 +8755,21 @@ func_mode_link ()
 	fi
       fi
 
-      test "$dlself" != no && \
-	func_warning "\`-dlopen self' is ignored for libtool libraries"
+      test no = "$dlself" \
+	|| func_warning "'-dlopen self' is ignored for libtool libraries"
 
       set dummy $rpath
       shift
-      test "$#" -gt 1 && \
-	func_warning "ignoring multiple \`-rpath's for a libtool library"
+      test 1 -lt "$#" \
+	&& func_warning "ignoring multiple '-rpath's for a libtool library"
 
-      install_libdir="$1"
+      install_libdir=$1
 
       oldlibs=
       if test -z "$rpath"; then
-	if test "$build_libtool_libs" = yes; then
+	if test yes = "$build_libtool_libs"; then
 	  # Building a libtool convenience library.
-	  # Some compilers have problems with a `.al' extension so
+	  # Some compilers have problems with a '.al' extension so
 	  # convenience libraries should have the same extension an
 	  # archive normally would.
 	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
@@ -7301,20 +8778,20 @@ func_mode_link ()
 	fi
 
 	test -n "$vinfo" && \
-	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"
+	  func_warning "'-version-info/-version-number' is ignored for convenience libraries"
 
 	test -n "$release" && \
-	  func_warning "\`-release' is ignored for convenience libraries"
+	  func_warning "'-release' is ignored for convenience libraries"
       else
 
 	# Parse the version information argument.
-	save_ifs="$IFS"; IFS=':'
+	save_ifs=$IFS; IFS=:
 	set dummy $vinfo 0 0 0
 	shift
-	IFS="$save_ifs"
+	IFS=$save_ifs
 
 	test -n "$7" && \
-	  func_fatal_help "too many parameters to \`-version-info'"
+	  func_fatal_help "too many parameters to '-version-info'"
 
 	# convert absolute version numbers to libtool ages
 	# this retains compatibility with .la files and attempts
@@ -7322,45 +8799,45 @@ func_mode_link ()
 
 	case $vinfo_number in
 	yes)
-	  number_major="$1"
-	  number_minor="$2"
-	  number_revision="$3"
+	  number_major=$1
+	  number_minor=$2
+	  number_revision=$3
 	  #
 	  # There are really only two kinds -- those that
 	  # use the current revision as the major version
 	  # and those that subtract age and use age as
 	  # a minor version.  But, then there is irix
-	  # which has an extra 1 added just for fun
+	  # that has an extra 1 added just for fun
 	  #
 	  case $version_type in
 	  # correct linux to gnu/linux during the next big refactor
-	  darwin|linux|osf|windows|none)
+	  darwin|freebsd-elf|linux|osf|windows|none)
 	    func_arith $number_major + $number_minor
 	    current=$func_arith_result
-	    age="$number_minor"
-	    revision="$number_revision"
+	    age=$number_minor
+	    revision=$number_revision
 	    ;;
-	  freebsd-aout|freebsd-elf|qnx|sunos)
-	    current="$number_major"
-	    revision="$number_minor"
-	    age="0"
+	  freebsd-aout|qnx|sunos)
+	    current=$number_major
+	    revision=$number_minor
+	    age=0
 	    ;;
 	  irix|nonstopux)
 	    func_arith $number_major + $number_minor
 	    current=$func_arith_result
-	    age="$number_minor"
-	    revision="$number_minor"
+	    age=$number_minor
+	    revision=$number_minor
 	    lt_irix_increment=no
 	    ;;
 	  *)
-	    func_fatal_configuration "$modename: unknown library version type \`$version_type'"
+	    func_fatal_configuration "$modename: unknown library version type '$version_type'"
 	    ;;
 	  esac
 	  ;;
 	no)
-	  current="$1"
-	  revision="$2"
-	  age="$3"
+	  current=$1
+	  revision=$2
+	  age=$3
 	  ;;
 	esac
 
@@ -7368,30 +8845,30 @@ func_mode_link ()
 	case $current in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  func_error "CURRENT \`$current' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
+	  func_error "CURRENT '$current' must be a nonnegative integer"
+	  func_fatal_error "'$vinfo' is not valid version information"
 	  ;;
 	esac
 
 	case $revision in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  func_error "REVISION \`$revision' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
+	  func_error "REVISION '$revision' must be a nonnegative integer"
+	  func_fatal_error "'$vinfo' is not valid version information"
 	  ;;
 	esac
 
 	case $age in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
 	*)
-	  func_error "AGE \`$age' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
+	  func_error "AGE '$age' must be a nonnegative integer"
+	  func_fatal_error "'$vinfo' is not valid version information"
 	  ;;
 	esac
 
 	if test "$age" -gt "$current"; then
-	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
-	  func_fatal_error "\`$vinfo' is not valid version information"
+	  func_error "AGE '$age' is greater than the current interface number '$current'"
+	  func_fatal_error "'$vinfo' is not valid version information"
 	fi
 
 	# Calculate the version variables.
@@ -7406,26 +8883,36 @@ func_mode_link ()
 	  # verstring for coding it into the library header
 	  func_arith $current - $age
 	  major=.$func_arith_result
-	  versuffix="$major.$age.$revision"
+	  versuffix=$major.$age.$revision
 	  # Darwin ld doesn't like 0 for these options...
 	  func_arith $current + 1
 	  minor_current=$func_arith_result
-	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
+	  xlcverstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision"
 	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+          # On Darwin other compilers
+          case $CC in
+              nagfor*)
+                  verstring="$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision"
+                  ;;
+              *)
+                  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
+                  ;;
+          esac
 	  ;;
 
 	freebsd-aout)
-	  major=".$current"
-	  versuffix=".$current.$revision";
+	  major=.$current
+	  versuffix=.$current.$revision
 	  ;;
 
 	freebsd-elf)
-	  major=".$current"
-	  versuffix=".$current"
+	  func_arith $current - $age
+	  major=.$func_arith_result
+	  versuffix=$major.$age.$revision
 	  ;;
 
 	irix | nonstopux)
-	  if test "X$lt_irix_increment" = "Xno"; then
+	  if test no = "$lt_irix_increment"; then
 	    func_arith $current - $age
 	  else
 	    func_arith $current - $age + 1
@@ -7436,69 +8923,74 @@ func_mode_link ()
 	    nonstopux) verstring_prefix=nonstopux ;;
 	    *)         verstring_prefix=sgi ;;
 	  esac
-	  verstring="$verstring_prefix$major.$revision"
+	  verstring=$verstring_prefix$major.$revision
 
 	  # Add in all the interfaces that we are compatible with.
 	  loop=$revision
-	  while test "$loop" -ne 0; do
+	  while test 0 -ne "$loop"; do
 	    func_arith $revision - $loop
 	    iface=$func_arith_result
 	    func_arith $loop - 1
 	    loop=$func_arith_result
-	    verstring="$verstring_prefix$major.$iface:$verstring"
+	    verstring=$verstring_prefix$major.$iface:$verstring
 	  done
 
-	  # Before this point, $major must not contain `.'.
+	  # Before this point, $major must not contain '.'.
 	  major=.$major
-	  versuffix="$major.$revision"
+	  versuffix=$major.$revision
 	  ;;
 
 	linux) # correct to gnu/linux during the next big refactor
 	  func_arith $current - $age
 	  major=.$func_arith_result
-	  versuffix="$major.$age.$revision"
+	  versuffix=$major.$age.$revision
 	  ;;
 
 	osf)
 	  func_arith $current - $age
 	  major=.$func_arith_result
-	  versuffix=".$current.$age.$revision"
-	  verstring="$current.$age.$revision"
+	  versuffix=.$current.$age.$revision
+	  verstring=$current.$age.$revision
 
 	  # Add in all the interfaces that we are compatible with.
 	  loop=$age
-	  while test "$loop" -ne 0; do
+	  while test 0 -ne "$loop"; do
 	    func_arith $current - $loop
 	    iface=$func_arith_result
 	    func_arith $loop - 1
 	    loop=$func_arith_result
-	    verstring="$verstring:${iface}.0"
+	    verstring=$verstring:$iface.0
 	  done
 
 	  # Make executables depend on our current version.
-	  func_append verstring ":${current}.0"
+	  func_append verstring ":$current.0"
 	  ;;
 
 	qnx)
-	  major=".$current"
-	  versuffix=".$current"
+	  major=.$current
+	  versuffix=.$current
+	  ;;
+
+	sco)
+	  major=.$current
+	  versuffix=.$current
 	  ;;
 
 	sunos)
-	  major=".$current"
-	  versuffix=".$current.$revision"
+	  major=.$current
+	  versuffix=.$current.$revision
 	  ;;
 
 	windows)
 	  # Use '-' rather than '.', since we only want one
-	  # extension on DOS 8.3 filesystems.
+	  # extension on DOS 8.3 file systems.
 	  func_arith $current - $age
 	  major=$func_arith_result
-	  versuffix="-$major"
+	  versuffix=-$major
 	  ;;
 
 	*)
-	  func_fatal_configuration "unknown library version type \`$version_type'"
+	  func_fatal_configuration "unknown library version type '$version_type'"
 	  ;;
 	esac
 
@@ -7512,42 +9004,45 @@ func_mode_link ()
 	    verstring=
 	    ;;
 	  *)
-	    verstring="0.0"
+	    verstring=0.0
 	    ;;
 	  esac
-	  if test "$need_version" = no; then
+	  if test no = "$need_version"; then
 	    versuffix=
 	  else
-	    versuffix=".0.0"
+	    versuffix=.0.0
 	  fi
 	fi
 
 	# Remove version info from name if versioning should be avoided
-	if test "$avoid_version" = yes && test "$need_version" = no; then
+	if test yes,no = "$avoid_version,$need_version"; then
 	  major=
 	  versuffix=
-	  verstring=""
+	  verstring=
 	fi
 
 	# Check to see if the archive will have undefined symbols.
-	if test "$allow_undefined" = yes; then
-	  if test "$allow_undefined_flag" = unsupported; then
-	    func_warning "undefined symbols not allowed in $host shared libraries"
-	    build_libtool_libs=no
-	    build_old_libs=yes
+	if test yes = "$allow_undefined"; then
+	  if test unsupported = "$allow_undefined_flag"; then
+	    if test yes = "$build_old_libs"; then
+	      func_warning "undefined symbols not allowed in $host shared libraries; building static only"
+	      build_libtool_libs=no
+	    else
+	      func_fatal_error "can't build $host shared library unless -no-undefined is specified"
+	    fi
 	  fi
 	else
 	  # Don't allow undefined symbols.
-	  allow_undefined_flag="$no_undefined_flag"
+	  allow_undefined_flag=$no_undefined_flag
 	fi
 
       fi
 
-      func_generate_dlsyms "$libname" "$libname" "yes"
+      func_generate_dlsyms "$libname" "$libname" :
       func_append libobjs " $symfileobj"
-      test "X$libobjs" = "X " && libobjs=
+      test " " = "$libobjs" && libobjs=
 
-      if test "$opt_mode" != relink; then
+      if test relink != "$opt_mode"; then
 	# Remove our outputs, but don't remove object files since they
 	# may have been created when compiling PIC objects.
 	removelist=
@@ -7556,8 +9051,8 @@ func_mode_link ()
 	  case $p in
 	    *.$objext | *.gcno)
 	       ;;
-	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
-	       if test "X$precious_files_regex" != "X"; then
+	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)
+	       if test -n "$precious_files_regex"; then
 		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
 		 then
 		   continue
@@ -7573,11 +9068,11 @@ func_mode_link ()
       fi
 
       # Now set the variables for building old libraries.
-      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
+      if test yes = "$build_old_libs" && test convenience != "$build_libtool_libs"; then
 	func_append oldlibs " $output_objdir/$libname.$libext"
 
 	# Transform .lo files to .o files.
-	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
+	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; $lo2o" | $NL2SP`
       fi
 
       # Eliminate all temporary directories.
@@ -7598,13 +9093,13 @@ func_mode_link ()
 	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
-	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
+	if test yes != "$hardcode_into_libs" || test yes = "$build_old_libs"; then
 	  dependency_libs="$temp_xrpath $dependency_libs"
 	fi
       fi
 
       # Make sure dlfiles contains only unique files that won't be dlpreopened
-      old_dlfiles="$dlfiles"
+      old_dlfiles=$dlfiles
       dlfiles=
       for lib in $old_dlfiles; do
 	case " $dlprefiles $dlfiles " in
@@ -7614,7 +9109,7 @@ func_mode_link ()
       done
 
       # Make sure dlprefiles contains only unique files
-      old_dlprefiles="$dlprefiles"
+      old_dlprefiles=$dlprefiles
       dlprefiles=
       for lib in $old_dlprefiles; do
 	case "$dlprefiles " in
@@ -7623,7 +9118,7 @@ func_mode_link ()
 	esac
       done
 
-      if test "$build_libtool_libs" = yes; then
+      if test yes = "$build_libtool_libs"; then
 	if test -n "$rpath"; then
 	  case $host in
 	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
@@ -7647,7 +9142,7 @@ func_mode_link ()
 	    ;;
 	  *)
 	    # Add libc to deplibs on all other systems if necessary.
-	    if test "$build_libtool_need_lc" = "yes"; then
+	    if test yes = "$build_libtool_need_lc"; then
 	      func_append deplibs " -lc"
 	    fi
 	    ;;
@@ -7663,9 +9158,9 @@ func_mode_link ()
 	# I'm not sure if I'm treating the release correctly.  I think
 	# release should show up in the -l (ie -lgmp5) so we don't want to
 	# add it in twice.  Is that correct?
-	release=""
-	versuffix=""
-	major=""
+	release=
+	versuffix=
+	major=
 	newdeplibs=
 	droppeddeps=no
 	case $deplibs_check_method in
@@ -7694,20 +9189,20 @@ EOF
 	      -l*)
 		func_stripname -l '' "$i"
 		name=$func_stripname_result
-		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		if test yes = "$allow_libtool_libs_with_static_runtimes"; then
 		  case " $predeps $postdeps " in
 		  *" $i "*)
 		    func_append newdeplibs " $i"
-		    i=""
+		    i=
 		    ;;
 		  esac
 		fi
-		if test -n "$i" ; then
+		if test -n "$i"; then
 		  libname=`eval "\\$ECHO \"$libname_spec\""`
 		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
 		  set dummy $deplib_matches; shift
 		  deplib_match=$1
-		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then
 		    func_append newdeplibs " $i"
 		  else
 		    droppeddeps=yes
@@ -7737,20 +9232,20 @@ EOF
 		$opt_dry_run || $RM conftest
 		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
 		  ldd_output=`ldd conftest`
-		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+		  if test yes = "$allow_libtool_libs_with_static_runtimes"; then
 		    case " $predeps $postdeps " in
 		    *" $i "*)
 		      func_append newdeplibs " $i"
-		      i=""
+		      i=
 		      ;;
 		    esac
 		  fi
-		  if test -n "$i" ; then
+		  if test -n "$i"; then
 		    libname=`eval "\\$ECHO \"$libname_spec\""`
 		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
 		    set dummy $deplib_matches; shift
 		    deplib_match=$1
-		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
+		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then
 		      func_append newdeplibs " $i"
 		    else
 		      droppeddeps=yes
@@ -7787,24 +9282,24 @@ EOF
 	    -l*)
 	      func_stripname -l '' "$a_deplib"
 	      name=$func_stripname_result
-	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	      if test yes = "$allow_libtool_libs_with_static_runtimes"; then
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
 		  func_append newdeplibs " $a_deplib"
-		  a_deplib=""
+		  a_deplib=
 		  ;;
 		esac
 	      fi
-	      if test -n "$a_deplib" ; then
+	      if test -n "$a_deplib"; then
 		libname=`eval "\\$ECHO \"$libname_spec\""`
 		if test -n "$file_magic_glob"; then
 		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
 		else
 		  libnameglob=$libname
 		fi
-		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
+		test yes = "$want_nocaseglob" && nocaseglob=`shopt -p nocaseglob`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  if test "$want_nocaseglob" = yes; then
+		  if test yes = "$want_nocaseglob"; then
 		    shopt -s nocaseglob
 		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
 		    $nocaseglob
@@ -7822,25 +9317,25 @@ EOF
 		      # We might still enter an endless loop, since a link
 		      # loop can be closed while we follow links,
 		      # but so what?
-		      potlib="$potent_lib"
+		      potlib=$potent_lib
 		      while test -h "$potlib" 2>/dev/null; do
-			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
+			potliblink=`ls -ld $potlib | $SED 's/.* -> //'`
 			case $potliblink in
-			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
-			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
+			[\\/]* | [A-Za-z]:[\\/]*) potlib=$potliblink;;
+			*) potlib=`$ECHO "$potlib" | $SED 's|[^/]*$||'`"$potliblink";;
 			esac
 		      done
 		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
 			 $SED -e 10q |
 			 $EGREP "$file_magic_regex" > /dev/null; then
 			func_append newdeplibs " $a_deplib"
-			a_deplib=""
+			a_deplib=
 			break 2
 		      fi
 		  done
 		done
 	      fi
-	      if test -n "$a_deplib" ; then
+	      if test -n "$a_deplib"; then
 		droppeddeps=yes
 		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
@@ -7848,7 +9343,7 @@ EOF
 		echo "*** you link to this library.  But I can only do this if you have a"
 		echo "*** shared version of the library, which you do not appear to have"
 		echo "*** because I did check the linker path looking for a file starting"
-		if test -z "$potlib" ; then
+		if test -z "$potlib"; then
 		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
 		else
 		  $ECHO "*** with $libname and none of the candidates passed a file format test"
@@ -7871,30 +9366,30 @@ EOF
 	    -l*)
 	      func_stripname -l '' "$a_deplib"
 	      name=$func_stripname_result
-	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
+	      if test yes = "$allow_libtool_libs_with_static_runtimes"; then
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
 		  func_append newdeplibs " $a_deplib"
-		  a_deplib=""
+		  a_deplib=
 		  ;;
 		esac
 	      fi
-	      if test -n "$a_deplib" ; then
+	      if test -n "$a_deplib"; then
 		libname=`eval "\\$ECHO \"$libname_spec\""`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
 		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
 		  for potent_lib in $potential_libs; do
-		    potlib="$potent_lib" # see symlink-check above in file_magic test
+		    potlib=$potent_lib # see symlink-check above in file_magic test
 		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
 		       $EGREP "$match_pattern_regex" > /dev/null; then
 		      func_append newdeplibs " $a_deplib"
-		      a_deplib=""
+		      a_deplib=
 		      break 2
 		    fi
 		  done
 		done
 	      fi
-	      if test -n "$a_deplib" ; then
+	      if test -n "$a_deplib"; then
 		droppeddeps=yes
 		echo
 		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
@@ -7902,7 +9397,7 @@ EOF
 		echo "*** you link to this library.  But I can only do this if you have a"
 		echo "*** shared version of the library, which you do not appear to have"
 		echo "*** because I did check the linker path looking for a file starting"
-		if test -z "$potlib" ; then
+		if test -z "$potlib"; then
 		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
 		else
 		  $ECHO "*** with $libname and none of the candidates passed a file format test"
@@ -7918,18 +9413,18 @@ EOF
 	  done # Gone through all deplibs.
 	  ;;
 	none | unknown | *)
-	  newdeplibs=""
+	  newdeplibs=
 	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
-	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-	    for i in $predeps $postdeps ; do
+	  if test yes = "$allow_libtool_libs_with_static_runtimes"; then
+	    for i in $predeps $postdeps; do
 	      # can't use Xsed below, because $i might contain '/'
-	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
+	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s|$i||"`
 	    done
 	  fi
 	  case $tmp_deplibs in
 	  *[!\	\ ]*)
 	    echo
-	    if test "X$deplibs_check_method" = "Xnone"; then
+	    if test none = "$deplibs_check_method"; then
 	      echo "*** Warning: inter-library dependencies are not supported in this platform."
 	    else
 	      echo "*** Warning: inter-library dependencies are not known to be supported."
@@ -7953,8 +9448,8 @@ EOF
 	  ;;
 	esac
 
-	if test "$droppeddeps" = yes; then
-	  if test "$module" = yes; then
+	if test yes = "$droppeddeps"; then
+	  if test yes = "$module"; then
 	    echo
 	    echo "*** Warning: libtool could not satisfy all declared inter-library"
 	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
@@ -7963,12 +9458,12 @@ EOF
 	    if test -z "$global_symbol_pipe"; then
 	      echo
 	      echo "*** However, this would only work if libtool was able to extract symbol"
-	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
+	      echo "*** lists from a program, using 'nm' or equivalent, but libtool could"
 	      echo "*** not find such a program.  So, this module is probably useless."
-	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	      echo "*** 'nm' from GNU binutils and a full rebuild may help."
 	    fi
-	    if test "$build_old_libs" = no; then
-	      oldlibs="$output_objdir/$libname.$libext"
+	    if test no = "$build_old_libs"; then
+	      oldlibs=$output_objdir/$libname.$libext
 	      build_libtool_libs=module
 	      build_old_libs=yes
 	    else
@@ -7979,14 +9474,14 @@ EOF
 	    echo "*** automatically added whenever a program is linked with this library"
 	    echo "*** or is declared to -dlopen it."
 
-	    if test "$allow_undefined" = no; then
+	    if test no = "$allow_undefined"; then
 	      echo
 	      echo "*** Since this library must not contain undefined symbols,"
 	      echo "*** because either the platform does not support them or"
 	      echo "*** it was explicitly requested with -no-undefined,"
 	      echo "*** libtool will only create a static version of it."
-	      if test "$build_old_libs" = no; then
-		oldlibs="$output_objdir/$libname.$libext"
+	      if test no = "$build_old_libs"; then
+		oldlibs=$output_objdir/$libname.$libext
 		build_libtool_libs=module
 		build_old_libs=yes
 	      else
@@ -8032,7 +9527,7 @@ EOF
 	*) func_append new_libs " $deplib" ;;
 	esac
       done
-      deplibs="$new_libs"
+      deplibs=$new_libs
 
       # All the library-specific variables (install_libdir is set above).
       library_names=
@@ -8040,25 +9535,25 @@ EOF
       dlname=
 
       # Test again, we may have decided not to build it any more
-      if test "$build_libtool_libs" = yes; then
-	# Remove ${wl} instances when linking with ld.
+      if test yes = "$build_libtool_libs"; then
+	# Remove $wl instances when linking with ld.
 	# FIXME: should test the right _cmds variable.
 	case $archive_cmds in
 	  *\$LD\ *) wl= ;;
         esac
-	if test "$hardcode_into_libs" = yes; then
+	if test yes = "$hardcode_into_libs"; then
 	  # Hardcode the library paths
 	  hardcode_libdirs=
 	  dep_rpath=
-	  rpath="$finalize_rpath"
-	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
+	  rpath=$finalize_rpath
+	  test relink = "$opt_mode" || rpath=$compile_rpath$rpath
 	  for libdir in $rpath; do
 	    if test -n "$hardcode_libdir_flag_spec"; then
 	      if test -n "$hardcode_libdir_separator"; then
 		func_replace_sysroot "$libdir"
 		libdir=$func_replace_sysroot_result
 		if test -z "$hardcode_libdirs"; then
-		  hardcode_libdirs="$libdir"
+		  hardcode_libdirs=$libdir
 		else
 		  # Just accumulate the unique libdirs.
 		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
@@ -8083,7 +9578,7 @@ EOF
 	  # Substitute the hardcoded libdirs into the rpath.
 	  if test -n "$hardcode_libdir_separator" &&
 	     test -n "$hardcode_libdirs"; then
-	    libdir="$hardcode_libdirs"
+	    libdir=$hardcode_libdirs
 	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
 	  fi
 	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
@@ -8097,8 +9592,8 @@ EOF
 	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
 	fi
 
-	shlibpath="$finalize_shlibpath"
-	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
+	shlibpath=$finalize_shlibpath
+	test relink = "$opt_mode" || shlibpath=$compile_shlibpath$shlibpath
 	if test -n "$shlibpath"; then
 	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
 	fi
@@ -8108,19 +9603,19 @@ EOF
 	eval library_names=\"$library_names_spec\"
 	set dummy $library_names
 	shift
-	realname="$1"
+	realname=$1
 	shift
 
 	if test -n "$soname_spec"; then
 	  eval soname=\"$soname_spec\"
 	else
-	  soname="$realname"
+	  soname=$realname
 	fi
 	if test -z "$dlname"; then
 	  dlname=$soname
 	fi
 
-	lib="$output_objdir/$realname"
+	lib=$output_objdir/$realname
 	linknames=
 	for link
 	do
@@ -8134,7 +9629,7 @@ EOF
 	delfiles=
 	if test -n "$export_symbols" && test -n "$include_expsyms"; then
 	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
-	  export_symbols="$output_objdir/$libname.uexp"
+	  export_symbols=$output_objdir/$libname.uexp
 	  func_append delfiles " $export_symbols"
 	fi
 
@@ -8143,31 +9638,31 @@ EOF
 	cygwin* | mingw* | cegcc*)
 	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
 	    # exporting using user supplied symfile
-	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
+	    func_dll_def_p "$export_symbols" || {
 	      # and it's NOT already a .def file. Must figure out
 	      # which of the given symbols are data symbols and tag
 	      # them as such. So, trigger use of export_symbols_cmds.
 	      # export_symbols gets reassigned inside the "prepare
 	      # the list of exported symbols" if statement, so the
 	      # include_expsyms logic still works.
-	      orig_export_symbols="$export_symbols"
+	      orig_export_symbols=$export_symbols
 	      export_symbols=
 	      always_export_symbols=yes
-	    fi
+	    }
 	  fi
 	  ;;
 	esac
 
 	# Prepare the list of exported symbols
 	if test -z "$export_symbols"; then
-	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
-	    func_verbose "generating symbol list for \`$libname.la'"
-	    export_symbols="$output_objdir/$libname.exp"
+	  if test yes = "$always_export_symbols" || test -n "$export_symbols_regex"; then
+	    func_verbose "generating symbol list for '$libname.la'"
+	    export_symbols=$output_objdir/$libname.exp
 	    $opt_dry_run || $RM $export_symbols
 	    cmds=$export_symbols_cmds
-	    save_ifs="$IFS"; IFS='~'
+	    save_ifs=$IFS; IFS='~'
 	    for cmd1 in $cmds; do
-	      IFS="$save_ifs"
+	      IFS=$save_ifs
 	      # Take the normal branch if the nm_file_list_spec branch
 	      # doesn't work or if tool conversion is not needed.
 	      case $nm_file_list_spec~$to_tool_file_cmd in
@@ -8181,7 +9676,7 @@ EOF
 		  try_normal_branch=no
 		  ;;
 	      esac
-	      if test "$try_normal_branch" = yes \
+	      if test yes = "$try_normal_branch" \
 		 && { test "$len" -lt "$max_cmd_len" \
 		      || test "$max_cmd_len" -le -1; }
 	      then
@@ -8192,7 +9687,7 @@ EOF
 		output_la=$func_basename_result
 		save_libobjs=$libobjs
 		save_output=$output
-		output=${output_objdir}/${output_la}.nm
+		output=$output_objdir/$output_la.nm
 		func_to_tool_file "$output"
 		libobjs=$nm_file_list_spec$func_to_tool_file_result
 		func_append delfiles " $output"
@@ -8215,8 +9710,8 @@ EOF
 		break
 	      fi
 	    done
-	    IFS="$save_ifs"
-	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
+	    IFS=$save_ifs
+	    if test -n "$export_symbols_regex" && test : != "$skipped_export"; then
 	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
 	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
 	    fi
@@ -8224,16 +9719,16 @@ EOF
 	fi
 
 	if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	  tmp_export_symbols="$export_symbols"
-	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	  tmp_export_symbols=$export_symbols
+	  test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols
 	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	fi
 
-	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
+	if test : != "$skipped_export" && test -n "$orig_export_symbols"; then
 	  # The given exports_symbols file has to be filtered, so filter it.
-	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	  func_verbose "filter symbol list for '$libname.la' to tag DATA exports"
 	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
-	  # 's' commands which not all seds can handle. GNU sed should be fine
+	  # 's' commands, which not all seds can handle. GNU sed should be fine
 	  # though. Also, the filter scales superlinearly with the number of
 	  # global variables. join(1) would be nice here, but unfortunately
 	  # isn't a blessed tool.
@@ -8252,11 +9747,11 @@ EOF
 	    ;;
 	  esac
 	done
-	deplibs="$tmp_deplibs"
+	deplibs=$tmp_deplibs
 
 	if test -n "$convenience"; then
 	  if test -n "$whole_archive_flag_spec" &&
-	    test "$compiler_needs_object" = yes &&
+	    test yes = "$compiler_needs_object" &&
 	    test -z "$libobjs"; then
 	    # extract the archives, so we have objects to list.
 	    # TODO: could optimize this to just extract one archive.
@@ -8267,7 +9762,7 @@ EOF
 	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
 	    test "X$libobjs" = "X " && libobjs=
 	  else
-	    gentop="$output_objdir/${outputname}x"
+	    gentop=$output_objdir/${outputname}x
 	    func_append generated " $gentop"
 
 	    func_extract_archives $gentop $convenience
@@ -8276,18 +9771,18 @@ EOF
 	  fi
 	fi
 
-	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
+	if test yes = "$thread_safe" && test -n "$thread_safe_flag_spec"; then
 	  eval flag=\"$thread_safe_flag_spec\"
 	  func_append linker_flags " $flag"
 	fi
 
 	# Make a backup of the uninstalled library when relinking
-	if test "$opt_mode" = relink; then
+	if test relink = "$opt_mode"; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
 	fi
 
 	# Do each of the archive commands.
-	if test "$module" = yes && test -n "$module_cmds" ; then
+	if test yes = "$module" && test -n "$module_cmds"; then
 	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
 	    eval test_cmds=\"$module_expsym_cmds\"
 	    cmds=$module_expsym_cmds
@@ -8305,7 +9800,7 @@ EOF
 	  fi
 	fi
 
-	if test "X$skipped_export" != "X:" &&
+	if test : != "$skipped_export" &&
 	   func_len " $test_cmds" &&
 	   len=$func_len_result &&
 	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
@@ -8338,8 +9833,8 @@ EOF
 	  last_robj=
 	  k=1
 
-	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
-	    output=${output_objdir}/${output_la}.lnkscript
+	  if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then
+	    output=$output_objdir/$output_la.lnkscript
 	    func_verbose "creating GNU ld script: $output"
 	    echo 'INPUT (' > $output
 	    for obj in $save_libobjs
@@ -8351,14 +9846,14 @@ EOF
 	    func_append delfiles " $output"
 	    func_to_tool_file "$output"
 	    output=$func_to_tool_file_result
-	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
-	    output=${output_objdir}/${output_la}.lnk
+	  elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then
+	    output=$output_objdir/$output_la.lnk
 	    func_verbose "creating linker input file list: $output"
 	    : > $output
 	    set x $save_libobjs
 	    shift
 	    firstobj=
-	    if test "$compiler_needs_object" = yes; then
+	    if test yes = "$compiler_needs_object"; then
 	      firstobj="$1 "
 	      shift
 	    fi
@@ -8373,7 +9868,7 @@ EOF
 	  else
 	    if test -n "$save_libobjs"; then
 	      func_verbose "creating reloadable object files..."
-	      output=$output_objdir/$output_la-${k}.$objext
+	      output=$output_objdir/$output_la-$k.$objext
 	      eval test_cmds=\"$reload_cmds\"
 	      func_len " $test_cmds"
 	      len0=$func_len_result
@@ -8385,13 +9880,13 @@ EOF
 		func_len " $obj"
 		func_arith $len + $func_len_result
 		len=$func_arith_result
-		if test "X$objlist" = X ||
+		if test -z "$objlist" ||
 		   test "$len" -lt "$max_cmd_len"; then
 		  func_append objlist " $obj"
 		else
 		  # The command $test_cmds is almost too long, add a
 		  # command to the queue.
-		  if test "$k" -eq 1 ; then
+		  if test 1 -eq "$k"; then
 		    # The first file doesn't have a previous command to add.
 		    reload_objs=$objlist
 		    eval concat_cmds=\"$reload_cmds\"
@@ -8401,10 +9896,10 @@ EOF
 		    reload_objs="$objlist $last_robj"
 		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
 		  fi
-		  last_robj=$output_objdir/$output_la-${k}.$objext
+		  last_robj=$output_objdir/$output_la-$k.$objext
 		  func_arith $k + 1
 		  k=$func_arith_result
-		  output=$output_objdir/$output_la-${k}.$objext
+		  output=$output_objdir/$output_la-$k.$objext
 		  objlist=" $obj"
 		  func_len " $last_robj"
 		  func_arith $len0 + $func_len_result
@@ -8416,9 +9911,9 @@ EOF
 	      # files will link in the last one created.
 	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
 	      reload_objs="$objlist $last_robj"
-	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
+	      eval concat_cmds=\"\$concat_cmds$reload_cmds\"
 	      if test -n "$last_robj"; then
-	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
+	        eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
 	      fi
 	      func_append delfiles " $output"
 
@@ -8426,9 +9921,9 @@ EOF
 	      output=
 	    fi
 
-	    if ${skipped_export-false}; then
-	      func_verbose "generating symbol list for \`$libname.la'"
-	      export_symbols="$output_objdir/$libname.exp"
+	    ${skipped_export-false} && {
+	      func_verbose "generating symbol list for '$libname.la'"
+	      export_symbols=$output_objdir/$libname.exp
 	      $opt_dry_run || $RM $export_symbols
 	      libobjs=$output
 	      # Append the command to create the export file.
@@ -8437,16 +9932,16 @@ EOF
 	      if test -n "$last_robj"; then
 		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
 	      fi
-	    fi
+	    }
 
 	    test -n "$save_libobjs" &&
 	      func_verbose "creating a temporary reloadable object file: $output"
 
 	    # Loop through the commands generated above and execute them.
-	    save_ifs="$IFS"; IFS='~'
+	    save_ifs=$IFS; IFS='~'
 	    for cmd in $concat_cmds; do
-	      IFS="$save_ifs"
-	      $opt_silent || {
+	      IFS=$save_ifs
+	      $opt_quiet || {
 		  func_quote_for_expand "$cmd"
 		  eval "func_echo $func_quote_for_expand_result"
 	      }
@@ -8454,7 +9949,7 @@ EOF
 		lt_exit=$?
 
 		# Restore the uninstalled library and exit
-		if test "$opt_mode" = relink; then
+		if test relink = "$opt_mode"; then
 		  ( cd "$output_objdir" && \
 		    $RM "${realname}T" && \
 		    $MV "${realname}U" "$realname" )
@@ -8463,7 +9958,7 @@ EOF
 		exit $lt_exit
 	      }
 	    done
-	    IFS="$save_ifs"
+	    IFS=$save_ifs
 
 	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
 	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
@@ -8471,18 +9966,18 @@ EOF
 	    fi
 	  fi
 
-          if ${skipped_export-false}; then
+          ${skipped_export-false} && {
 	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	      tmp_export_symbols="$export_symbols"
-	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
+	      tmp_export_symbols=$export_symbols
+	      test -n "$orig_export_symbols" && tmp_export_symbols=$orig_export_symbols
 	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
 	    fi
 
 	    if test -n "$orig_export_symbols"; then
 	      # The given exports_symbols file has to be filtered, so filter it.
-	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	      func_verbose "filter symbol list for '$libname.la' to tag DATA exports"
 	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
-	      # 's' commands which not all seds can handle. GNU sed should be fine
+	      # 's' commands, which not all seds can handle. GNU sed should be fine
 	      # though. Also, the filter scales superlinearly with the number of
 	      # global variables. join(1) would be nice here, but unfortunately
 	      # isn't a blessed tool.
@@ -8491,7 +9986,7 @@ EOF
 	      export_symbols=$output_objdir/$libname.def
 	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
 	    fi
-	  fi
+	  }
 
 	  libobjs=$output
 	  # Restore the value of output.
@@ -8505,7 +10000,7 @@ EOF
 	  # value of $libobjs for piecewise linking.
 
 	  # Do each of the archive commands.
-	  if test "$module" = yes && test -n "$module_cmds" ; then
+	  if test yes = "$module" && test -n "$module_cmds"; then
 	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
 	      cmds=$module_expsym_cmds
 	    else
@@ -8527,7 +10022,7 @@ EOF
 
 	# Add any objects from preloaded convenience libraries
 	if test -n "$dlprefiles"; then
-	  gentop="$output_objdir/${outputname}x"
+	  gentop=$output_objdir/${outputname}x
 	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
@@ -8535,11 +10030,12 @@ EOF
 	  test "X$libobjs" = "X " && libobjs=
 	fi
 
-	save_ifs="$IFS"; IFS='~'
+	save_ifs=$IFS; IFS='~'
 	for cmd in $cmds; do
-	  IFS="$save_ifs"
+	  IFS=$sp$nl
 	  eval cmd=\"$cmd\"
-	  $opt_silent || {
+	  IFS=$save_ifs
+	  $opt_quiet || {
 	    func_quote_for_expand "$cmd"
 	    eval "func_echo $func_quote_for_expand_result"
 	  }
@@ -8547,7 +10043,7 @@ EOF
 	    lt_exit=$?
 
 	    # Restore the uninstalled library and exit
-	    if test "$opt_mode" = relink; then
+	    if test relink = "$opt_mode"; then
 	      ( cd "$output_objdir" && \
 	        $RM "${realname}T" && \
 		$MV "${realname}U" "$realname" )
@@ -8556,10 +10052,10 @@ EOF
 	    exit $lt_exit
 	  }
 	done
-	IFS="$save_ifs"
+	IFS=$save_ifs
 
 	# Restore the uninstalled library and exit
-	if test "$opt_mode" = relink; then
+	if test relink = "$opt_mode"; then
 	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
 
 	  if test -n "$convenience"; then
@@ -8579,39 +10075,39 @@ EOF
 	done
 
 	# If -module or -export-dynamic was specified, set the dlname.
-	if test "$module" = yes || test "$export_dynamic" = yes; then
+	if test yes = "$module" || test yes = "$export_dynamic"; then
 	  # On all known operating systems, these are identical.
-	  dlname="$soname"
+	  dlname=$soname
 	fi
       fi
       ;;
 
     obj)
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
-	func_warning "\`-dlopen' is ignored for objects"
+      if test -n "$dlfiles$dlprefiles" || test no != "$dlself"; then
+	func_warning "'-dlopen' is ignored for objects"
       fi
 
       case " $deplibs" in
       *\ -l* | *\ -L*)
-	func_warning "\`-l' and \`-L' are ignored for objects" ;;
+	func_warning "'-l' and '-L' are ignored for objects" ;;
       esac
 
       test -n "$rpath" && \
-	func_warning "\`-rpath' is ignored for objects"
+	func_warning "'-rpath' is ignored for objects"
 
       test -n "$xrpath" && \
-	func_warning "\`-R' is ignored for objects"
+	func_warning "'-R' is ignored for objects"
 
       test -n "$vinfo" && \
-	func_warning "\`-version-info' is ignored for objects"
+	func_warning "'-version-info' is ignored for objects"
 
       test -n "$release" && \
-	func_warning "\`-release' is ignored for objects"
+	func_warning "'-release' is ignored for objects"
 
       case $output in
       *.lo)
 	test -n "$objs$old_deplibs" && \
-	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"
+	  func_fatal_error "cannot build library object '$output' from non-libtool objects"
 
 	libobj=$output
 	func_lo2o "$libobj"
@@ -8619,7 +10115,7 @@ EOF
 	;;
       *)
 	libobj=
-	obj="$output"
+	obj=$output
 	;;
       esac
 
@@ -8632,17 +10128,19 @@ EOF
       # the extraction.
       reload_conv_objs=
       gentop=
-      # reload_cmds runs $LD directly, so let us get rid of
-      # -Wl from whole_archive_flag_spec and hope we can get by with
-      # turning comma into space..
-      wl=
-
+      # if reload_cmds runs $LD directly, get rid of -Wl from
+      # whole_archive_flag_spec and hope we can get by with turning comma
+      # into space.
+      case $reload_cmds in
+        *\$LD[\ \$]*) wl= ;;
+      esac
       if test -n "$convenience"; then
 	if test -n "$whole_archive_flag_spec"; then
 	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
-	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
+	  test -n "$wl" || tmp_whole_archive_flags=`$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
+	  reload_conv_objs=$reload_objs\ $tmp_whole_archive_flags
 	else
-	  gentop="$output_objdir/${obj}x"
+	  gentop=$output_objdir/${obj}x
 	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $convenience
@@ -8651,12 +10149,12 @@ EOF
       fi
 
       # If we're not building shared, we need to use non_pic_objs
-      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
+      test yes = "$build_libtool_libs" || libobjs=$non_pic_objects
 
       # Create the old-style object.
-      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
+      reload_objs=$objs$old_deplibs' '`$ECHO "$libobjs" | $SP2NL | $SED "/\.$libext$/d; /\.lib$/d; $lo2o" | $NL2SP`' '$reload_conv_objs
 
-      output="$obj"
+      output=$obj
       func_execute_cmds "$reload_cmds" 'exit $?'
 
       # Exit if we aren't doing a library object file.
@@ -8668,7 +10166,7 @@ EOF
 	exit $EXIT_SUCCESS
       fi
 
-      if test "$build_libtool_libs" != yes; then
+      test yes = "$build_libtool_libs" || {
 	if test -n "$gentop"; then
 	  func_show_eval '${RM}r "$gentop"'
 	fi
@@ -8678,12 +10176,12 @@ EOF
 	# $show "echo timestamp > $libobj"
 	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
 	exit $EXIT_SUCCESS
-      fi
+      }
 
-      if test -n "$pic_flag" || test "$pic_mode" != default; then
+      if test -n "$pic_flag" || test default != "$pic_mode"; then
 	# Only do commands if we really have different PIC objects.
 	reload_objs="$libobjs $reload_conv_objs"
-	output="$libobj"
+	output=$libobj
 	func_execute_cmds "$reload_cmds" 'exit $?'
       fi
 
@@ -8700,16 +10198,14 @@ EOF
 	          output=$func_stripname_result.exe;;
       esac
       test -n "$vinfo" && \
-	func_warning "\`-version-info' is ignored for programs"
+	func_warning "'-version-info' is ignored for programs"
 
       test -n "$release" && \
-	func_warning "\`-release' is ignored for programs"
+	func_warning "'-release' is ignored for programs"
 
-      test "$preload" = yes \
-        && test "$dlopen_support" = unknown \
-	&& test "$dlopen_self" = unknown \
-	&& test "$dlopen_self_static" = unknown && \
-	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."
+      $preload \
+	&& test unknown,unknown,unknown = "$dlopen_support,$dlopen_self,$dlopen_self_static" \
+	&& func_warning "'LT_INIT([dlopen])' not used. Assuming no dlopen support."
 
       case $host in
       *-*-rhapsody* | *-*-darwin1.[012])
@@ -8723,11 +10219,11 @@ EOF
       *-*-darwin*)
 	# Don't allow lazy linking, it breaks C++ global constructors
 	# But is supposedly fixed on 10.4 or later (yay!).
-	if test "$tagname" = CXX ; then
+	if test CXX = "$tagname"; then
 	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
 	    10.[0123])
-	      func_append compile_command " ${wl}-bind_at_load"
-	      func_append finalize_command " ${wl}-bind_at_load"
+	      func_append compile_command " $wl-bind_at_load"
+	      func_append finalize_command " $wl-bind_at_load"
 	    ;;
 	  esac
 	fi
@@ -8763,7 +10259,7 @@ EOF
 	*) func_append new_libs " $deplib" ;;
 	esac
       done
-      compile_deplibs="$new_libs"
+      compile_deplibs=$new_libs
 
 
       func_append compile_command " $compile_deplibs"
@@ -8787,7 +10283,7 @@ EOF
 	if test -n "$hardcode_libdir_flag_spec"; then
 	  if test -n "$hardcode_libdir_separator"; then
 	    if test -z "$hardcode_libdirs"; then
-	      hardcode_libdirs="$libdir"
+	      hardcode_libdirs=$libdir
 	    else
 	      # Just accumulate the unique libdirs.
 	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
@@ -8810,7 +10306,7 @@ EOF
 	fi
 	case $host in
 	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
+	  testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$libdir:"*) ;;
 	  ::) dllsearchpath=$libdir;;
@@ -8827,10 +10323,10 @@ EOF
       # Substitute the hardcoded libdirs into the rpath.
       if test -n "$hardcode_libdir_separator" &&
 	 test -n "$hardcode_libdirs"; then
-	libdir="$hardcode_libdirs"
+	libdir=$hardcode_libdirs
 	eval rpath=\" $hardcode_libdir_flag_spec\"
       fi
-      compile_rpath="$rpath"
+      compile_rpath=$rpath
 
       rpath=
       hardcode_libdirs=
@@ -8838,7 +10334,7 @@ EOF
 	if test -n "$hardcode_libdir_flag_spec"; then
 	  if test -n "$hardcode_libdir_separator"; then
 	    if test -z "$hardcode_libdirs"; then
-	      hardcode_libdirs="$libdir"
+	      hardcode_libdirs=$libdir
 	    else
 	      # Just accumulate the unique libdirs.
 	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
@@ -8863,45 +10359,43 @@ EOF
       # Substitute the hardcoded libdirs into the rpath.
       if test -n "$hardcode_libdir_separator" &&
 	 test -n "$hardcode_libdirs"; then
-	libdir="$hardcode_libdirs"
+	libdir=$hardcode_libdirs
 	eval rpath=\" $hardcode_libdir_flag_spec\"
       fi
-      finalize_rpath="$rpath"
+      finalize_rpath=$rpath
 
-      if test -n "$libobjs" && test "$build_old_libs" = yes; then
+      if test -n "$libobjs" && test yes = "$build_old_libs"; then
 	# Transform all the library objects into standard objects.
 	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
 	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
       fi
 
-      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
+      func_generate_dlsyms "$outputname" "@PROGRAM@" false
 
       # template prelinking step
       if test -n "$prelink_cmds"; then
 	func_execute_cmds "$prelink_cmds" 'exit $?'
       fi
 
-      wrappers_required=yes
+      wrappers_required=:
       case $host in
       *cegcc* | *mingw32ce*)
         # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
-        wrappers_required=no
+        wrappers_required=false
         ;;
       *cygwin* | *mingw* )
-        if test "$build_libtool_libs" != yes; then
-          wrappers_required=no
-        fi
+        test yes = "$build_libtool_libs" || wrappers_required=false
         ;;
       *)
-        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
-          wrappers_required=no
+        if test no = "$need_relink" || test yes != "$build_libtool_libs"; then
+          wrappers_required=false
         fi
         ;;
       esac
-      if test "$wrappers_required" = no; then
+      $wrappers_required || {
 	# Replace the output file specification.
 	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
-	link_command="$compile_command$compile_rpath"
+	link_command=$compile_command$compile_rpath
 
 	# We have no uninstalled library dependencies, so finalize right now.
 	exit_status=0
@@ -8914,12 +10408,12 @@ EOF
 	fi
 
 	# Delete the generated files.
-	if test -f "$output_objdir/${outputname}S.${objext}"; then
-	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
+	if test -f "$output_objdir/${outputname}S.$objext"; then
+	  func_show_eval '$RM "$output_objdir/${outputname}S.$objext"'
 	fi
 
 	exit $exit_status
-      fi
+      }
 
       if test -n "$compile_shlibpath$finalize_shlibpath"; then
 	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
@@ -8949,9 +10443,9 @@ EOF
 	fi
       fi
 
-      if test "$no_install" = yes; then
+      if test yes = "$no_install"; then
 	# We don't need to create a wrapper script.
-	link_command="$compile_var$compile_command$compile_rpath"
+	link_command=$compile_var$compile_command$compile_rpath
 	# Replace the output file specification.
 	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	# Delete the old output file.
@@ -8968,27 +10462,28 @@ EOF
 	exit $EXIT_SUCCESS
       fi
 
-      if test "$hardcode_action" = relink; then
-	# Fast installation is not supported
-	link_command="$compile_var$compile_command$compile_rpath"
-	relink_command="$finalize_var$finalize_command$finalize_rpath"
+      case $hardcode_action,$fast_install in
+        relink,*)
+	  # Fast installation is not supported
+	  link_command=$compile_var$compile_command$compile_rpath
+	  relink_command=$finalize_var$finalize_command$finalize_rpath
 
-	func_warning "this platform does not like uninstalled shared libraries"
-	func_warning "\`$output' will be relinked during installation"
-      else
-	if test "$fast_install" != no; then
-	  link_command="$finalize_var$compile_command$finalize_rpath"
-	  if test "$fast_install" = yes; then
-	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
-	  else
-	    # fast_install is set to needless
-	    relink_command=
-	  fi
-	else
-	  link_command="$compile_var$compile_command$compile_rpath"
-	  relink_command="$finalize_var$finalize_command$finalize_rpath"
-	fi
-      fi
+	  func_warning "this platform does not like uninstalled shared libraries"
+	  func_warning "'$output' will be relinked during installation"
+	  ;;
+        *,yes)
+	  link_command=$finalize_var$compile_command$finalize_rpath
+	  relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
+          ;;
+	*,no)
+	  link_command=$compile_var$compile_command$compile_rpath
+	  relink_command=$finalize_var$finalize_command$finalize_rpath
+          ;;
+	*,needless)
+	  link_command=$finalize_var$compile_command$finalize_rpath
+	  relink_command=
+          ;;
+      esac
 
       # Replace the output file specification.
       link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
@@ -9045,8 +10540,8 @@ EOF
 	    func_dirname_and_basename "$output" "" "."
 	    output_name=$func_basename_result
 	    output_path=$func_dirname_result
-	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
-	    cwrapper="$output_path/$output_name.exe"
+	    cwrappersource=$output_path/$objdir/lt-$output_name.c
+	    cwrapper=$output_path/$output_name.exe
 	    $RM $cwrappersource $cwrapper
 	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
 
@@ -9067,7 +10562,7 @@ EOF
 	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
 	    $opt_dry_run || {
 	      # note: this script will not be executed, so do not chmod.
-	      if test "x$build" = "x$host" ; then
+	      if test "x$build" = "x$host"; then
 		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
 	      else
 		func_emit_wrapper no > $func_ltwrapper_scriptname_result
@@ -9090,25 +10585,27 @@ EOF
     # See if we need to build an old-fashioned archive.
     for oldlib in $oldlibs; do
 
-      if test "$build_libtool_libs" = convenience; then
-	oldobjs="$libobjs_save $symfileobj"
-	addlibs="$convenience"
-	build_libtool_libs=no
-      else
-	if test "$build_libtool_libs" = module; then
-	  oldobjs="$libobjs_save"
+      case $build_libtool_libs in
+        convenience)
+	  oldobjs="$libobjs_save $symfileobj"
+	  addlibs=$convenience
 	  build_libtool_libs=no
-	else
+	  ;;
+	module)
+	  oldobjs=$libobjs_save
+	  addlibs=$old_convenience
+	  build_libtool_libs=no
+          ;;
+	*)
 	  oldobjs="$old_deplibs $non_pic_objects"
-	  if test "$preload" = yes && test -f "$symfileobj"; then
-	    func_append oldobjs " $symfileobj"
-	  fi
-	fi
-	addlibs="$old_convenience"
-      fi
+	  $preload && test -f "$symfileobj" \
+	    && func_append oldobjs " $symfileobj"
+	  addlibs=$old_convenience
+	  ;;
+      esac
 
       if test -n "$addlibs"; then
-	gentop="$output_objdir/${outputname}x"
+	gentop=$output_objdir/${outputname}x
 	func_append generated " $gentop"
 
 	func_extract_archives $gentop $addlibs
@@ -9116,13 +10613,13 @@ EOF
       fi
 
       # Do each command in the archive commands.
-      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
+      if test -n "$old_archive_from_new_cmds" && test yes = "$build_libtool_libs"; then
 	cmds=$old_archive_from_new_cmds
       else
 
 	# Add any objects from preloaded convenience libraries
 	if test -n "$dlprefiles"; then
-	  gentop="$output_objdir/${outputname}x"
+	  gentop=$output_objdir/${outputname}x
 	  func_append generated " $gentop"
 
 	  func_extract_archives $gentop $dlprefiles
@@ -9143,7 +10640,7 @@ EOF
 	  :
 	else
 	  echo "copying selected object files to avoid basename conflicts..."
-	  gentop="$output_objdir/${outputname}x"
+	  gentop=$output_objdir/${outputname}x
 	  func_append generated " $gentop"
 	  func_mkdir_p "$gentop"
 	  save_oldobjs=$oldobjs
@@ -9152,7 +10649,7 @@ EOF
 	  for obj in $save_oldobjs
 	  do
 	    func_basename "$obj"
-	    objbase="$func_basename_result"
+	    objbase=$func_basename_result
 	    case " $oldobjs " in
 	    " ") oldobjs=$obj ;;
 	    *[\ /]"$objbase "*)
@@ -9221,18 +10718,18 @@ EOF
 	    else
 	      # the above command should be used before it gets too long
 	      oldobjs=$objlist
-	      if test "$obj" = "$last_oldobj" ; then
+	      if test "$obj" = "$last_oldobj"; then
 		RANLIB=$save_RANLIB
 	      fi
 	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
+	      eval concat_cmds=\"\$concat_cmds$old_archive_cmds\"
 	      objlist=
 	      len=$len0
 	    fi
 	  done
 	  RANLIB=$save_RANLIB
 	  oldobjs=$objlist
-	  if test "X$oldobjs" = "X" ; then
+	  if test -z "$oldobjs"; then
 	    eval cmds=\"\$concat_cmds\"
 	  else
 	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
@@ -9249,7 +10746,7 @@ EOF
     case $output in
     *.la)
       old_library=
-      test "$build_old_libs" = yes && old_library="$libname.$libext"
+      test yes = "$build_old_libs" && old_library=$libname.$libext
       func_verbose "creating $output"
 
       # Preserve any variables that may affect compiler behavior
@@ -9264,31 +10761,31 @@ EOF
 	fi
       done
       # Quote the link command for shipping.
-      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
+      relink_command="(cd `pwd`; $SHELL \"$progpath\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
       relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
-      if test "$hardcode_automatic" = yes ; then
+      if test yes = "$hardcode_automatic"; then
 	relink_command=
       fi
 
       # Only create the output if not a dry run.
       $opt_dry_run || {
 	for installed in no yes; do
-	  if test "$installed" = yes; then
+	  if test yes = "$installed"; then
 	    if test -z "$install_libdir"; then
 	      break
 	    fi
-	    output="$output_objdir/$outputname"i
+	    output=$output_objdir/${outputname}i
 	    # Replace all uninstalled libtool libraries with the installed ones
 	    newdependency_libs=
 	    for deplib in $dependency_libs; do
 	      case $deplib in
 	      *.la)
 		func_basename "$deplib"
-		name="$func_basename_result"
+		name=$func_basename_result
 		func_resolve_sysroot "$deplib"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
+		eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
 		test -z "$libdir" && \
-		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		  func_fatal_error "'$deplib' is not a valid libtool archive"
 		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
 		;;
 	      -L*)
@@ -9304,23 +10801,23 @@ EOF
 	      *) func_append newdependency_libs " $deplib" ;;
 	      esac
 	    done
-	    dependency_libs="$newdependency_libs"
+	    dependency_libs=$newdependency_libs
 	    newdlfiles=
 
 	    for lib in $dlfiles; do
 	      case $lib in
 	      *.la)
 	        func_basename "$lib"
-		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		name=$func_basename_result
+		eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
 		test -z "$libdir" && \
-		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		  func_fatal_error "'$lib' is not a valid libtool archive"
 		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
 	      *) func_append newdlfiles " $lib" ;;
 	      esac
 	    done
-	    dlfiles="$newdlfiles"
+	    dlfiles=$newdlfiles
 	    newdlprefiles=
 	    for lib in $dlprefiles; do
 	      case $lib in
@@ -9330,34 +10827,34 @@ EOF
 		# didn't already link the preopened objects directly into
 		# the library:
 		func_basename "$lib"
-		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
+		name=$func_basename_result
+		eval libdir=`$SED -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
 		test -z "$libdir" && \
-		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		  func_fatal_error "'$lib' is not a valid libtool archive"
 		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
 		;;
 	      esac
 	    done
-	    dlprefiles="$newdlprefiles"
+	    dlprefiles=$newdlprefiles
 	  else
 	    newdlfiles=
 	    for lib in $dlfiles; do
 	      case $lib in
-		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		[\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;;
 		*) abs=`pwd`"/$lib" ;;
 	      esac
 	      func_append newdlfiles " $abs"
 	    done
-	    dlfiles="$newdlfiles"
+	    dlfiles=$newdlfiles
 	    newdlprefiles=
 	    for lib in $dlprefiles; do
 	      case $lib in
-		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
+		[\\/]* | [A-Za-z]:[\\/]*) abs=$lib ;;
 		*) abs=`pwd`"/$lib" ;;
 	      esac
 	      func_append newdlprefiles " $abs"
 	    done
-	    dlprefiles="$newdlprefiles"
+	    dlprefiles=$newdlprefiles
 	  fi
 	  $RM $output
 	  # place dlname in correct position for cygwin
@@ -9373,10 +10870,9 @@ EOF
 	  case $host,$output,$installed,$module,$dlname in
 	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
 	      # If a -bindir argument was supplied, place the dll there.
-	      if test "x$bindir" != x ;
-	      then
+	      if test -n "$bindir"; then
 		func_relative_path "$install_libdir" "$bindir"
-		tdlname=$func_relative_path_result$dlname
+		tdlname=$func_relative_path_result/$dlname
 	      else
 		# Otherwise fall back on heuristic.
 		tdlname=../bin/$dlname
@@ -9385,7 +10881,7 @@ EOF
 	  esac
 	  $ECHO > $output "\
 # $outputname - a libtool library file
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+# Generated by $PROGRAM (GNU $PACKAGE) $VERSION
 #
 # Please DO NOT delete this file!
 # It is necessary for linking the library.
@@ -9399,7 +10895,7 @@ library_names='$library_names'
 # The name of the static archive.
 old_library='$old_library'
 
-# Linker flags that can not go in dependency_libs.
+# Linker flags that cannot go in dependency_libs.
 inherited_linker_flags='$new_inherited_linker_flags'
 
 # Libraries that this one depends upon.
@@ -9425,7 +10921,7 @@ dlpreopen='$dlprefiles'
 
 # Directory that this library needs to be installed in:
 libdir='$install_libdir'"
-	  if test "$installed" = no && test "$need_relink" = yes; then
+	  if test no,yes = "$installed,$need_relink"; then
 	    $ECHO >> $output "\
 relink_command=\"$relink_command\""
 	  fi
@@ -9440,27 +10936,29 @@ relink_command=\"$relink_command\""
     exit $EXIT_SUCCESS
 }
 
-{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
-    func_mode_link ${1+"$@"}
+if test link = "$opt_mode" || test relink = "$opt_mode"; then
+  func_mode_link ${1+"$@"}
+fi
 
 
 # func_mode_uninstall arg...
 func_mode_uninstall ()
 {
-    $opt_debug
-    RM="$nonopt"
+    $debug_cmd
+
+    RM=$nonopt
     files=
-    rmforce=
+    rmforce=false
     exit_status=0
 
     # This variable tells wrapper scripts just to set variables rather
     # than running their programs.
-    libtool_install_magic="$magic"
+    libtool_install_magic=$magic
 
     for arg
     do
       case $arg in
-      -f) func_append RM " $arg"; rmforce=yes ;;
+      -f) func_append RM " $arg"; rmforce=: ;;
       -*) func_append RM " $arg" ;;
       *) func_append files " $arg" ;;
       esac
@@ -9473,18 +10971,18 @@ func_mode_uninstall ()
 
     for file in $files; do
       func_dirname "$file" "" "."
-      dir="$func_dirname_result"
-      if test "X$dir" = X.; then
-	odir="$objdir"
+      dir=$func_dirname_result
+      if test . = "$dir"; then
+	odir=$objdir
       else
-	odir="$dir/$objdir"
+	odir=$dir/$objdir
       fi
       func_basename "$file"
-      name="$func_basename_result"
-      test "$opt_mode" = uninstall && odir="$dir"
+      name=$func_basename_result
+      test uninstall = "$opt_mode" && odir=$dir
 
       # Remember odir for removal later, being careful to avoid duplicates
-      if test "$opt_mode" = clean; then
+      if test clean = "$opt_mode"; then
 	case " $rmdirs " in
 	  *" $odir "*) ;;
 	  *) func_append rmdirs " $odir" ;;
@@ -9499,11 +10997,11 @@ func_mode_uninstall ()
       elif test -d "$file"; then
 	exit_status=1
 	continue
-      elif test "$rmforce" = yes; then
+      elif $rmforce; then
 	continue
       fi
 
-      rmfiles="$file"
+      rmfiles=$file
 
       case $name in
       *.la)
@@ -9517,7 +11015,7 @@ func_mode_uninstall ()
 	  done
 	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
 
-	  case "$opt_mode" in
+	  case $opt_mode in
 	  clean)
 	    case " $library_names " in
 	    *" $dlname "*) ;;
@@ -9528,12 +11026,12 @@ func_mode_uninstall ()
 	  uninstall)
 	    if test -n "$library_names"; then
 	      # Do each command in the postuninstall commands.
-	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	      func_execute_cmds "$postuninstall_cmds" '$rmforce || exit_status=1'
 	    fi
 
 	    if test -n "$old_library"; then
 	      # Do each command in the old_postuninstall commands.
-	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
+	      func_execute_cmds "$old_postuninstall_cmds" '$rmforce || exit_status=1'
 	    fi
 	    # FIXME: should reinstall the best remaining shared library.
 	    ;;
@@ -9549,21 +11047,19 @@ func_mode_uninstall ()
 	  func_source $dir/$name
 
 	  # Add PIC object to the list of files to remove.
-	  if test -n "$pic_object" &&
-	     test "$pic_object" != none; then
+	  if test -n "$pic_object" && test none != "$pic_object"; then
 	    func_append rmfiles " $dir/$pic_object"
 	  fi
 
 	  # Add non-PIC object to the list of files to remove.
-	  if test -n "$non_pic_object" &&
-	     test "$non_pic_object" != none; then
+	  if test -n "$non_pic_object" && test none != "$non_pic_object"; then
 	    func_append rmfiles " $dir/$non_pic_object"
 	  fi
 	fi
 	;;
 
       *)
-	if test "$opt_mode" = clean ; then
+	if test clean = "$opt_mode"; then
 	  noexename=$name
 	  case $file in
 	  *.exe)
@@ -9590,12 +11086,12 @@ func_mode_uninstall ()
 
 	    # note $name still contains .exe if it was in $file originally
 	    # as does the version of $file that was added into $rmfiles
-	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
-	    if test "$fast_install" = yes && test -n "$relink_command"; then
+	    func_append rmfiles " $odir/$name $odir/${name}S.$objext"
+	    if test yes = "$fast_install" && test -n "$relink_command"; then
 	      func_append rmfiles " $odir/lt-$name"
 	    fi
-	    if test "X$noexename" != "X$name" ; then
-	      func_append rmfiles " $odir/lt-${noexename}.c"
+	    if test "X$noexename" != "X$name"; then
+	      func_append rmfiles " $odir/lt-$noexename.c"
 	    fi
 	  fi
 	fi
@@ -9604,7 +11100,7 @@ func_mode_uninstall ()
       func_show_eval "$RM $rmfiles" 'exit_status=1'
     done
 
-    # Try to remove the ${objdir}s in the directories where we deleted files
+    # Try to remove the $objdir's in the directories where we deleted files
     for dir in $rmdirs; do
       if test -d "$dir"; then
 	func_show_eval "rmdir $dir >/dev/null 2>&1"
@@ -9614,16 +11110,17 @@ func_mode_uninstall ()
     exit $exit_status
 }
 
-{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
-    func_mode_uninstall ${1+"$@"}
+if test uninstall = "$opt_mode" || test clean = "$opt_mode"; then
+  func_mode_uninstall ${1+"$@"}
+fi
 
 test -z "$opt_mode" && {
-  help="$generic_help"
+  help=$generic_help
   func_fatal_help "you must specify a MODE"
 }
 
 test -z "$exec_cmd" && \
-  func_fatal_help "invalid operation mode \`$opt_mode'"
+  func_fatal_help "invalid operation mode '$opt_mode'"
 
 if test -n "$exec_cmd"; then
   eval exec "$exec_cmd"
@@ -9634,7 +11131,7 @@ exit $exit_status
 
 
 # The TAGs below are defined such that we never get into a situation
-# in which we disable both kinds of libraries.  Given conflicting
+# where we disable both kinds of libraries.  Given conflicting
 # choices, we go for a static library, that is the most portable,
 # since we can't tell whether shared libraries were disabled because
 # the user asked for that or because the platform doesn't support
@@ -9657,5 +11154,3 @@ build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
 # mode:shell-script
 # sh-indentation:2
 # End:
-# vi:sw=2
-
diff --git a/autostuff/missing b/autostuff/missing
index db98974..f62bbae 100755
--- a/autostuff/missing
+++ b/autostuff/missing
@@ -3,7 +3,7 @@
 
 scriptversion=2013-10-28.13; # UTC
 
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+# Copyright (C) 1996-2014 Free Software Foundation, Inc.
 # Originally written by Fran,cois Pinard <pinard at iro.umontreal.ca>, 1996.
 
 # This program is free software; you can redistribute it and/or modify
diff --git a/autostuff/test-driver b/autostuff/test-driver
index d306056..8e575b0 100755
--- a/autostuff/test-driver
+++ b/autostuff/test-driver
@@ -3,7 +3,7 @@
 
 scriptversion=2013-07-13.22; # UTC
 
-# Copyright (C) 2011-2013 Free Software Foundation, Inc.
+# Copyright (C) 2011-2014 Free Software Foundation, Inc.
 #
 # 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
@@ -106,11 +106,14 @@ trap "st=143; $do_exit" 15
 # Test script is run here.
 "$@" >$log_file 2>&1
 estatus=$?
+
 if test $enable_hard_errors = no && test $estatus -eq 99; then
-  estatus=1
+  tweaked_estatus=1
+else
+  tweaked_estatus=$estatus
 fi
 
-case $estatus:$expect_failure in
+case $tweaked_estatus:$expect_failure in
   0:yes) col=$red res=XPASS recheck=yes gcopy=yes;;
   0:*)   col=$grn res=PASS  recheck=no  gcopy=no;;
   77:*)  col=$blu res=SKIP  recheck=no  gcopy=yes;;
@@ -119,6 +122,12 @@ case $estatus:$expect_failure in
   *:*)   col=$red res=FAIL  recheck=yes gcopy=yes;;
 esac
 
+# Report the test outcome and exit status in the logs, so that one can
+# know whether the test passed or failed simply by looking at the '.log'
+# file, without the need of also peaking into the corresponding '.trs'
+# file (automake bug#11814).
+echo "$res $test_name (exit status: $estatus)" >>$log_file
+
 # Report outcome to console.
 echo "${col}${res}${std}: $test_name"
 
diff --git a/config.h.in b/config.h.in
index 207fa28..c104af9 100644
--- a/config.h.in
+++ b/config.h.in
@@ -1,8 +1,5 @@
 /* config.h.in.  Generated from configure.ac by autoheader.  */
 
-#ifndef SRD_CONFIG_H
-#define SRD_CONFIG_H    /* To stop multiple inclusions. */
-
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #undef HAVE_DLFCN_H
 
@@ -33,13 +30,9 @@
 /* Define to 1 if you have the <unistd.h> header file. */
 #undef HAVE_UNISTD_H
 
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
 #undef LT_OBJDIR
 
-/* Name of package */
-#undef PACKAGE
-
 /* Define to the address where bug reports for this package should be sent. */
 #undef PACKAGE_BUGREPORT
 
@@ -58,10 +51,45 @@
 /* Define to the version of this package. */
 #undef PACKAGE_VERSION
 
+/* Binary age of libsigrokdecode. */
+#undef SRD_LIB_VERSION_AGE
+
+/* Binary version of libsigrokdecode. */
+#undef SRD_LIB_VERSION_CURRENT
+
+/* Binary revision of libsigrokdecode. */
+#undef SRD_LIB_VERSION_REVISION
+
+/* Binary version triple of libsigrokdecode. */
+#undef SRD_LIB_VERSION_STRING
+
+/* Major version number of libsigrokdecode. */
+#undef SRD_PACKAGE_VERSION_MAJOR
+
+/* Micro version number of libsigrokdecode. */
+#undef SRD_PACKAGE_VERSION_MICRO
+
+/* Minor version number of libsigrokdecode. */
+#undef SRD_PACKAGE_VERSION_MINOR
+
+/* Version of libsigrokdecode. */
+#undef SRD_PACKAGE_VERSION_STRING
+
 /* Define to 1 if you have the ANSI C header files. */
 #undef STDC_HEADERS
 
-/* Version number of package */
-#undef VERSION
+/* Enable large inode numbers on Mac OS X 10.5.  */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
 
-#endif /* SRD_CONFIG_H */
+/* The targeted POSIX standard. */
+#ifndef _POSIX_C_SOURCE
+# define _POSIX_C_SOURCE 200112L
+#endif
diff --git a/configure b/configure
index 5216848..a95b545 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for libsigrokdecode 0.3.0.
+# Generated by GNU Autoconf 2.69 for libsigrokdecode 0.4.1.
 #
 # Report bugs to <sigrok-devel at lists.sourceforge.net>.
 #
@@ -590,8 +590,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='libsigrokdecode'
 PACKAGE_TARNAME='libsigrokdecode'
-PACKAGE_VERSION='0.3.0'
-PACKAGE_STRING='libsigrokdecode 0.3.0'
+PACKAGE_VERSION='0.4.1'
+PACKAGE_STRING='libsigrokdecode 0.4.1'
 PACKAGE_BUGREPORT='sigrok-devel at lists.sourceforge.net'
 PACKAGE_URL='http://www.sigrok.org'
 
@@ -635,48 +635,27 @@ ac_subst_vars='am__EXEEXT_FALSE
 am__EXEEXT_TRUE
 LTLIBOBJS
 LIBOBJS
-BUILD_RUNTC_FALSE
-BUILD_RUNTC_TRUE
-SRD_PACKAGE_VERSION
-SRD_PACKAGE_VERSION_MICRO
-SRD_PACKAGE_VERSION_MINOR
-SRD_PACKAGE_VERSION_MAJOR
-AM_LIBTOOLFLAGS
-MAKEFLAGS
-DECODERS_DIR
-LIBSIGROK_LIBS
-LIBSIGROK_CFLAGS
-libsigrok_LIBS
-libsigrok_CFLAGS
+TESTS_LIBS
+TESTS_CFLAGS
+LIBSIGROKDECODE_LIBS
+LIBSIGROKDECODE_CFLAGS
+SRD_PKGLIBS
+SRD_EXTRA_LIBS
+SRD_WFLAGS
+SRD_EXTRA_CFLAGS
 HAVE_CHECK_FALSE
 HAVE_CHECK_TRUE
-check_LIBS
-check_CFLAGS
 PYTHON3
-LDFLAGS_PYTHON
-CPPFLAGS_PYTHON
-python32_LIBS
-python32_CFLAGS
-python33_LIBS
-python33_CFLAGS
-python34_LIBS
-python34_CFLAGS
-python3_LIBS
-python3_CFLAGS
-GLIB_COMPILE_RESOURCES
-GLIB_MKENUMS
-GOBJECT_QUERY
-GLIB_GENMARSHAL
-GLIB_LIBS
-GLIB_CFLAGS
-SRD_LIB_LDFLAGS
-SRD_LIB_VERSION
-SRD_LIB_VERSION_AGE
-SRD_LIB_VERSION_REVISION
-SRD_LIB_VERSION_CURRENT
 PKG_CONFIG_LIBDIR
 PKG_CONFIG_PATH
 PKG_CONFIG
+WIN32_FALSE
+WIN32_TRUE
+SRD_LIB_VERSION
+SRD_PACKAGE_VERSION
+CONFIG_STATUS_DEPENDENCIES
+CPP
+LT_SYS_LIBRARY_PATH
 OTOOL64
 OTOOL
 LIPO
@@ -694,6 +673,8 @@ FGREP
 EGREP
 GREP
 SED
+LIBTOOL
+LN_S
 host_os
 host_vendor
 host_cpu
@@ -702,9 +683,6 @@ build_os
 build_vendor
 build_cpu
 build
-LIBTOOL
-LN_S
-CPP
 am__fastdepCC_FALSE
 am__fastdepCC_TRUE
 CCDEPMODE
@@ -770,6 +748,7 @@ infodir
 docdir
 oldincludedir
 includedir
+runstatedir
 localstatedir
 sharedstatedir
 sysconfdir
@@ -798,10 +777,12 @@ enable_shared
 enable_static
 with_pic
 enable_fast_install
+with_aix_soname
 with_gnu_ld
 with_sysroot
 enable_libtool_lock
-enable_glibtest
+enable_warnings
+enable_largefile
 '
       ac_precious_vars='build_alias
 host_alias
@@ -811,22 +792,16 @@ CFLAGS
 LDFLAGS
 LIBS
 CPPFLAGS
+LT_SYS_LIBRARY_PATH
 CPP
 PKG_CONFIG
 PKG_CONFIG_PATH
 PKG_CONFIG_LIBDIR
-python3_CFLAGS
-python3_LIBS
-python34_CFLAGS
-python34_LIBS
-python33_CFLAGS
-python33_LIBS
-python32_CFLAGS
-python32_LIBS
-check_CFLAGS
-check_LIBS
-libsigrok_CFLAGS
-libsigrok_LIBS'
+PYTHON3
+LIBSIGROKDECODE_CFLAGS
+LIBSIGROKDECODE_LIBS
+TESTS_CFLAGS
+TESTS_LIBS'
 
 
 # Initialize some variables set by options.
@@ -865,6 +840,7 @@ datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
+runstatedir='${localstatedir}/run'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
 docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
@@ -1117,6 +1093,15 @@ do
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
 
+  -runstatedir | --runstatedir | --runstatedi | --runstated \
+  | --runstate | --runstat | --runsta | --runst | --runs \
+  | --run | --ru | --r)
+    ac_prev=runstatedir ;;
+  -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
+  | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
+  | --run=* | --ru=* | --r=*)
+    runstatedir=$ac_optarg ;;
+
   -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
@@ -1254,7 +1239,7 @@ fi
 for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
 		datadir sysconfdir sharedstatedir localstatedir includedir \
 		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-		libdir localedir mandir
+		libdir localedir mandir runstatedir
 do
   eval ac_val=\$$ac_var
   # Remove trailing slashes.
@@ -1367,7 +1352,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures libsigrokdecode 0.3.0 to adapt to many kinds of systems.
+\`configure' configures libsigrokdecode 0.4.1 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1407,6 +1392,7 @@ Fine tuning of the installation directories:
   --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
   --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
   --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --runstatedir=DIR       modifiable per-process data [LOCALSTATEDIR/run]
   --libdir=DIR            object code libraries [EPREFIX/lib]
   --includedir=DIR        C header files [PREFIX/include]
   --oldincludedir=DIR     C header files for non-gcc [/usr/include]
@@ -1437,7 +1423,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of libsigrokdecode 0.3.0:";;
+     short | recursive ) echo "Configuration of libsigrokdecode 0.4.1:";;
    esac
   cat <<\_ACEOF
 
@@ -1456,16 +1442,21 @@ Optional Features:
   --enable-fast-install[=PKGS]
                           optimize for fast installation [default=yes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
-  --disable-glibtest      do not try to compile and run a test GLIB program
+  --enable-warnings[=min|max|fatal|no]
+                          set compile pedantry level [default=max]
+  --disable-largefile     omit support for large files
 
 Optional Packages:
   --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
   --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
   --with-pic[=PKGS]       try to use only PIC/non-PIC objects [default=use
                           both]
+  --with-aix-soname=aix|svr4|both
+                          shared library versioning (aka "SONAME") variant to
+                          provide on AIX, [default=aix].
   --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
-  --with-sysroot=DIR Search for dependent libraries within DIR
-                        (or the compiler's sysroot if not specified).
+  --with-sysroot[=DIR]    Search for dependent libraries within DIR (or the
+                          compiler's sysroot if not specified).
 
 Some influential environment variables:
   CC          C compiler command
@@ -1475,35 +1466,22 @@ Some influential environment variables:
   LIBS        libraries to pass to the linker, e.g. -l<library>
   CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
               you have headers in a nonstandard directory <include dir>
+  LT_SYS_LIBRARY_PATH
+              User-defined run-time library search path.
   CPP         C preprocessor
   PKG_CONFIG  path to pkg-config utility
   PKG_CONFIG_PATH
               directories to add to pkg-config's search path
   PKG_CONFIG_LIBDIR
               path overriding pkg-config's built-in search path
-  python3_CFLAGS
-              C compiler flags for python3, overriding pkg-config
-  python3_LIBS
-              linker flags for python3, overriding pkg-config
-  python34_CFLAGS
-              C compiler flags for python34, overriding pkg-config
-  python34_LIBS
-              linker flags for python34, overriding pkg-config
-  python33_CFLAGS
-              C compiler flags for python33, overriding pkg-config
-  python33_LIBS
-              linker flags for python33, overriding pkg-config
-  python32_CFLAGS
-              C compiler flags for python32, overriding pkg-config
-  python32_LIBS
-              linker flags for python32, overriding pkg-config
-  check_CFLAGS
-              C compiler flags for check, overriding pkg-config
-  check_LIBS  linker flags for check, overriding pkg-config
-  libsigrok_CFLAGS
-              C compiler flags for libsigrok, overriding pkg-config
-  libsigrok_LIBS
-              linker flags for libsigrok, overriding pkg-config
+  PYTHON3     Python 3 interpreter
+  LIBSIGROKDECODE_CFLAGS
+              C compiler flags for LIBSIGROKDECODE, overriding pkg-config
+  LIBSIGROKDECODE_LIBS
+              linker flags for LIBSIGROKDECODE, overriding pkg-config
+  TESTS_CFLAGS
+              C compiler flags for TESTS, overriding pkg-config
+  TESTS_LIBS  linker flags for TESTS, overriding pkg-config
 
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
@@ -1572,7 +1550,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-libsigrokdecode configure 0.3.0
+libsigrokdecode configure 0.4.1
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1624,43 +1602,6 @@ fi
 
 } # ac_fn_c_try_compile
 
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } > conftest.i && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-    ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
 # ac_fn_c_try_link LINENO
 # -----------------------
 # Try to link conftest.$ac_ext, and return whether this succeeded.
@@ -1738,6 +1679,43 @@ $as_echo "$ac_res" >&6; }
 
 } # ac_fn_c_check_header_compile
 
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
 # ac_fn_c_try_run LINENO
 # ----------------------
 # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
@@ -1846,102 +1824,11 @@ $as_echo "$ac_res" >&6; }
   eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_func
-
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval \${$3+:} false; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_header_compiler=yes
-else
-  ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  ac_header_preproc=yes
-else
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
-  yes:no: )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-  no:yes:* )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-( $as_echo "## ------------------------------------------------- ##
-## Report this to sigrok-devel at lists.sourceforge.net ##
-## ------------------------------------------------- ##"
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
 cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by libsigrokdecode $as_me 0.3.0, which was
+It was created by libsigrokdecode $as_me 0.4.1, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -2289,8 +2176,6 @@ ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-ac_config_headers="$ac_config_headers config.h"
-
 
 ac_aux_dir=
 for ac_dir in autostuff "$srcdir"/autostuff; do
@@ -2321,9 +2206,11 @@ ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
 ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
 
 
+ac_config_headers="$ac_config_headers config.h version.h"
+
 
 # We require at least automake 1.11 (needed for 'silent rules').
-am__api_version='1.14'
+am__api_version='1.15'
 
 # Find a good install program.  We prefer a C program (faster),
 # so one script is as good as another.  But avoid the broken or
@@ -2495,8 +2382,8 @@ test "$program_suffix" != NONE &&
 ac_script='s/[\\$]/&&/g;s/;s,x,x,$//'
 program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"`
 
-# expand $ac_aux_dir to an absolute path
-am_aux_dir=`cd $ac_aux_dir && pwd`
+# Expand $ac_aux_dir to an absolute path.
+am_aux_dir=`cd "$ac_aux_dir" && pwd`
 
 if test x"${MISSING+set}" != xset; then
   case $am_aux_dir in
@@ -2515,7 +2402,7 @@ else
 $as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;}
 fi
 
-if test x"${install_sh}" != xset; then
+if test x"${install_sh+set}" != xset; then
   case $am_aux_dir in
   *\ * | *\	*)
     install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
@@ -2809,18 +2696,9 @@ fi
 
 # Define the identity of the package.
  PACKAGE='libsigrokdecode'
- VERSION='0.3.0'
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE "$PACKAGE"
-_ACEOF
+ VERSION='0.4.1'
 
 
-cat >>confdefs.h <<_ACEOF
-#define VERSION "$VERSION"
-_ACEOF
-
 # Some tools Automake needs.
 
 ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"}
@@ -2843,8 +2721,8 @@ MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"}
 # <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
 mkdir_p='$(MKDIR_P)'
 
-# We need awk for the "check" target.  The system "awk" is bad on
-# some platforms.
+# We need awk for the "check" target (and possibly the TAP driver).  The
+# system "awk" is bad on some platforms.
 # Always define AMTAR for backward compatibility.  Yes, it's still used
 # in the wild :-(  We should find a proper way to deprecate it ...
 AMTAR='$${TAR-tar}'
@@ -4153,12 +4031,77 @@ unknown)
 esac
 
 
+# Make sure we can run config.sub.
+$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
+  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
+$as_echo_n "checking build system type... " >&6; }
+if ${ac_cv_build+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_build_alias=$build_alias
+test "x$ac_build_alias" = x &&
+  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
+test "x$ac_build_alias" = x &&
+  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
+ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
+  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
+$as_echo "$ac_cv_build" >&6; }
+case $ac_cv_build in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
+esac
+build=$ac_cv_build
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_build
+shift
+build_cpu=$1
+build_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+build_os=$*
+IFS=$ac_save_IFS
+case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
+$as_echo_n "checking host system type... " >&6; }
+if ${ac_cv_host+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "x$host_alias" = x; then
+  ac_cv_host=$ac_cv_build
+else
+  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
+    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
+fi
 
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
+$as_echo "$ac_cv_host" >&6; }
+case $ac_cv_host in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
+esac
+host=$ac_cv_host
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_host
+shift
+host_cpu=$1
+host_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+host_os=$*
+IFS=$ac_save_IFS
+case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
 
 
-# Enable more compiler warnings via -Wall and -Wextra. Add -fvisibility=hidden
-# and enforce use of SRD_API to explicitly mark all public API functions.
-CFLAGS="$CFLAGS -Wall -Wextra -Wmissing-prototypes -fvisibility=hidden"
 
 # Checks for programs.
 ac_ext=c
@@ -4887,158 +4830,33 @@ else
 fi
 
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
+$as_echo_n "checking whether ln -s works... " >&6; }
+LN_S=$as_ln_s
+if test "$LN_S" = "ln -s"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-  break
-fi
-
-    done
-    ac_cv_prog_CPP=$CPP
-
-fi
-  CPP=$ac_cv_prog_CPP
-else
-  ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
+$as_echo "no, using $LN_S" >&6; }
 fi
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
+# Required for per-target flags or subdir-objects with C sources.
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
-$as_echo_n "checking whether ln -s works... " >&6; }
-LN_S=$as_ln_s
-if test "$LN_S" = "ln -s"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
-$as_echo "no, using $LN_S" >&6; }
-fi
 
+# Set the standard the C library headers should conform to.
 
-# Required for per-target flags or subdir-objects with C sources.
 
+# Get compiler versions.
+sr_prog_ver=`$CC --version 2>&5 | sed 1q 2>&5`
+case $?:$sr_prog_ver in #(
+  0:*[0-9].[0-9]*) :
+    srd_cc_version=$sr_prog_ver ;; #(
+  *) :
+    srd_cc_version=unknown ;;
+esac
 
 # Initialize libtool.
 case `pwd` in
@@ -5049,13 +4867,8 @@ esac
 
 
 
-macro_version='2.4.2'
-macro_revision='1.3337'
-
-
-
-
-
+macro_version='2.4.6'
+macro_revision='2.4.6'
 
 
 
@@ -5064,78 +4877,12 @@ macro_revision='1.3337'
 
 
 
-ltmain="$ac_aux_dir/ltmain.sh"
-
-# Make sure we can run config.sub.
-$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
-  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
-$as_echo_n "checking build system type... " >&6; }
-if ${ac_cv_build+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_build_alias=$build_alias
-test "x$ac_build_alias" = x &&
-  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
-test "x$ac_build_alias" = x &&
-  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
-ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
-  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
 
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
-$as_echo "$ac_cv_build" >&6; }
-case $ac_cv_build in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
-esac
-build=$ac_cv_build
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_build
-shift
-build_cpu=$1
-build_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-build_os=$*
-IFS=$ac_save_IFS
-case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
-$as_echo_n "checking host system type... " >&6; }
-if ${ac_cv_host+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test "x$host_alias" = x; then
-  ac_cv_host=$ac_cv_build
-else
-  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
-    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
-fi
 
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
-$as_echo "$ac_cv_host" >&6; }
-case $ac_cv_host in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
-esac
-host=$ac_cv_host
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_host
-shift
-host_cpu=$1
-host_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-host_os=$*
-IFS=$ac_save_IFS
-case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
 
+ltmain=$ac_aux_dir/ltmain.sh
 
 # Backslashify metacharacters that are still active within
 # double-quoted strings.
@@ -5184,7 +4931,7 @@ func_echo_all ()
     $ECHO ""
 }
 
-case "$ECHO" in
+case $ECHO in
   printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
 $as_echo "printf" >&6; } ;;
   print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
@@ -5507,19 +5254,19 @@ test -z "$GREP" && GREP=grep
 
 # Check whether --with-gnu-ld was given.
 if test "${with_gnu_ld+set}" = set; then :
-  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
+  withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes
 else
   with_gnu_ld=no
 fi
 
 ac_prog=ld
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   # Check if gcc -print-prog-name=ld gives a path.
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
 $as_echo_n "checking for ld used by $CC... " >&6; }
   case $host in
   *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
+    # gcc leaves a trailing carriage return, which upsets mingw
     ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
   *)
     ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
@@ -5533,7 +5280,7 @@ $as_echo_n "checking for ld used by $CC... " >&6; }
       while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
 	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
       done
-      test -z "$LD" && LD="$ac_prog"
+      test -z "$LD" && LD=$ac_prog
       ;;
   "")
     # If it fails, then pretend we aren't using GCC.
@@ -5544,7 +5291,7 @@ $as_echo_n "checking for ld used by $CC... " >&6; }
     with_gnu_ld=unknown
     ;;
   esac
-elif test "$with_gnu_ld" = yes; then
+elif test yes = "$with_gnu_ld"; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
 $as_echo_n "checking for GNU ld... " >&6; }
 else
@@ -5555,32 +5302,32 @@ if ${lt_cv_path_LD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
   for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
     test -z "$ac_dir" && ac_dir=.
     if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
+      lt_cv_path_LD=$ac_dir/$ac_prog
       # Check to see if the program is GNU ld.  I'd rather use --version,
       # but apparently some variants of GNU ld only accept -v.
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
       *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
+	test no != "$with_gnu_ld" && break
 	;;
       *)
-	test "$with_gnu_ld" != yes && break
+	test yes != "$with_gnu_ld" && break
 	;;
       esac
     fi
   done
-  IFS="$lt_save_ifs"
+  IFS=$lt_save_ifs
 else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+  lt_cv_path_LD=$LD # Let the user override the test with a path.
 fi
 fi
 
-LD="$lt_cv_path_LD"
+LD=$lt_cv_path_LD
 if test -n "$LD"; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
 $as_echo "$LD" >&6; }
@@ -5623,33 +5370,38 @@ if ${lt_cv_path_NM+:} false; then :
 else
   if test -n "$NM"; then
   # Let the user override the test.
-  lt_cv_path_NM="$NM"
+  lt_cv_path_NM=$NM
 else
-  lt_nm_to_check="${ac_tool_prefix}nm"
+  lt_nm_to_check=${ac_tool_prefix}nm
   if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
     lt_nm_to_check="$lt_nm_to_check nm"
   fi
   for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
     for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+      tmp_nm=$ac_dir/$lt_tmp_nm
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then
 	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	# Adding the 'sed 1q' prevents false positives on HP-UX, which says:
 	#   nm: unknown option "B" ignored
 	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
+	# MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty
+	case $build_os in
+	mingw*) lt_bad_file=conftest.nm/nofile ;;
+	*) lt_bad_file=/dev/null ;;
+	esac
+	case `"$tmp_nm" -B $lt_bad_file 2>&1 | sed '1q'` in
+	*$lt_bad_file* | *'Invalid file or object type'*)
 	  lt_cv_path_NM="$tmp_nm -B"
-	  break
+	  break 2
 	  ;;
 	*)
 	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
 	  */dev/null*)
 	    lt_cv_path_NM="$tmp_nm -p"
-	    break
+	    break 2
 	    ;;
 	  *)
 	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
@@ -5660,15 +5412,15 @@ else
 	esac
       fi
     done
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
   done
   : ${lt_cv_path_NM=no}
 fi
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
 $as_echo "$lt_cv_path_NM" >&6; }
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
+if test no != "$lt_cv_path_NM"; then
+  NM=$lt_cv_path_NM
 else
   # Didn't find any BSD compatible name lister, look for dumpbin.
   if test -n "$DUMPBIN"; then :
@@ -5774,9 +5526,9 @@ esac
   fi
 fi
 
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    case `$DUMPBIN -symbols -headers /dev/null 2>&1 | sed '1q'` in
     *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
+      DUMPBIN="$DUMPBIN -symbols -headers"
       ;;
     *)
       DUMPBIN=:
@@ -5784,8 +5536,8 @@ fi
     esac
   fi
 
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
+  if test : != "$DUMPBIN"; then
+    NM=$DUMPBIN
   fi
 fi
 test -z "$NM" && NM=nm
@@ -5825,7 +5577,7 @@ if ${lt_cv_sys_max_cmd_len+:} false; then :
   $as_echo_n "(cached) " >&6
 else
     i=0
-  teststring="ABCD"
+  teststring=ABCD
 
   case $build_os in
   msdosdjgpp*)
@@ -5865,7 +5617,7 @@ else
     lt_cv_sys_max_cmd_len=8192;
     ;;
 
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+  bitrig* | darwin* | dragonfly* | freebsd* | netbsd* | openbsd*)
     # This has been around since 386BSD, at least.  Likely further.
     if test -x /sbin/sysctl; then
       lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
@@ -5916,22 +5668,22 @@ else
   *)
     lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
     if test -n "$lt_cv_sys_max_cmd_len" && \
-	test undefined != "$lt_cv_sys_max_cmd_len"; then
+       test undefined != "$lt_cv_sys_max_cmd_len"; then
       lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
       lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
     else
       # Make teststring a little bigger before we do anything with it.
       # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
+      for i in 1 2 3 4 5 6 7 8; do
         teststring=$teststring$teststring
       done
       SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
       # If test is not a shell built-in, we'll probably end up computing a
       # maximum length that is only half of the actual maximum length, but
       # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+      while { test X`env echo "$teststring$teststring" 2>/dev/null` \
 	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
+	      test 17 != "$i" # 1/2 MB should be enough
       do
         i=`expr $i + 1`
         teststring=$teststring$teststring
@@ -5949,7 +5701,7 @@ else
 
 fi
 
-if test -n $lt_cv_sys_max_cmd_len ; then
+if test -n "$lt_cv_sys_max_cmd_len"; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5
 $as_echo "$lt_cv_sys_max_cmd_len" >&6; }
 else
@@ -5967,30 +5719,6 @@ max_cmd_len=$lt_cv_sys_max_cmd_len
 : ${MV="mv -f"}
 : ${RM="rm -f"}
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5
-$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; }
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
-$as_echo "$xsi_shell" >&6; }
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5
-$as_echo_n "checking whether the shell understands \"+=\"... " >&6; }
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
-$as_echo "$lt_shell_append" >&6; }
-
-
 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
   lt_unset=unset
 else
@@ -6113,13 +5841,13 @@ esac
 reload_cmds='$LD$reload_flag -o $output$reload_objs'
 case $host_os in
   cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
+    if test yes != "$GCC"; then
       reload_cmds=false
     fi
     ;;
   darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    if test yes = "$GCC"; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib $wl-r -o $output$reload_objs'
     else
       reload_cmds='$LD$reload_flag -o $output$reload_objs'
     fi
@@ -6247,13 +5975,13 @@ lt_cv_deplibs_check_method='unknown'
 # Need to set the preceding variable on all platforms that support
 # interlibrary dependencies.
 # 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
+# 'unknown' -- same as none, but documents that we really don't know.
 # 'pass_all' -- all dependencies passed with no checks.
 # 'test_compile' -- check by making test program.
 # 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
+# that responds to the $file_magic_cmd with a given extended regex.
+# If you have 'file' or equivalent on your system and you're not sure
+# whether 'pass_all' will *always* work, you probably want this one.
 
 case $host_os in
 aix[4-9]*)
@@ -6280,8 +6008,7 @@ mingw* | pw32*)
   # Base MSYS/MinGW do not provide the 'file' command needed by
   # func_win32_libid shell function, so use a weaker test based on 'objdump',
   # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+  if ( file / ) >/dev/null 2>&1; then
     lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
     lt_cv_file_magic_cmd='func_win32_libid'
   else
@@ -6377,8 +6104,8 @@ newos6*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+openbsd* | bitrig*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
     lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
   else
     lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
@@ -6431,6 +6158,9 @@ sysv4 | sysv4.3*)
 tpf*)
   lt_cv_deplibs_check_method=pass_all
   ;;
+os2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 esac
 
 fi
@@ -6588,8 +6318,8 @@ else
 
 case $host_os in
 cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
+  # two different shell functions defined in ltmain.sh;
+  # decide which one to use based on capabilities of $DLLTOOL
   case `$DLLTOOL --help 2>&1` in
   *--identify-strict*)
     lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
@@ -6601,7 +6331,7 @@ cygwin* | mingw* | pw32* | cegcc*)
   ;;
 *)
   # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  lt_cv_sharedlib_from_linklib_cmd=$ECHO
   ;;
 esac
 
@@ -6755,7 +6485,7 @@ if ac_fn_c_try_compile "$LINENO"; then :
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }
-      if test "$ac_status" -eq 0; then
+      if test 0 -eq "$ac_status"; then
 	# Ensure the archiver fails upon bogus file names.
 	rm -f conftest.$ac_objext libconftest.a
 	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
@@ -6763,7 +6493,7 @@ if ac_fn_c_try_compile "$LINENO"; then :
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }
-	if test "$ac_status" -ne 0; then
+	if test 0 -ne "$ac_status"; then
           lt_cv_ar_at_file=@
         fi
       fi
@@ -6776,7 +6506,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
 $as_echo "$lt_cv_ar_at_file" >&6; }
 
-if test "x$lt_cv_ar_at_file" = xno; then
+if test no = "$lt_cv_ar_at_file"; then
   archiver_list_spec=
 else
   archiver_list_spec=$lt_cv_ar_at_file
@@ -6993,7 +6723,7 @@ old_postuninstall_cmds=
 
 if test -n "$RANLIB"; then
   case $host_os in
-  openbsd*)
+  bitrig* | openbsd*)
     old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
     ;;
   *)
@@ -7083,7 +6813,7 @@ cygwin* | mingw* | pw32* | cegcc*)
   symcode='[ABCDGISTW]'
   ;;
 hpux*)
-  if test "$host_cpu" = ia64; then
+  if test ia64 = "$host_cpu"; then
     symcode='[ABCDEGRST]'
   fi
   ;;
@@ -7116,14 +6846,44 @@ case `$NM -V 2>&1` in
   symcode='[ABCDGIRSTW]' ;;
 esac
 
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  # Gets list of data symbols to import.
+  lt_cv_sys_global_symbol_to_import="sed -n -e 's/^I .* \(.*\)$/\1/p'"
+  # Adjust the below global symbol transforms to fixup imported variables.
+  lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'"
+  lt_c_name_hook=" -e 's/^I .* \(.*\)$/  {\"\1\", (void *) 0},/p'"
+  lt_c_name_lib_hook="\
+  -e 's/^I .* \(lib.*\)$/  {\"\1\", (void *) 0},/p'\
+  -e 's/^I .* \(.*\)$/  {\"lib\1\", (void *) 0},/p'"
+else
+  # Disable hooks by default.
+  lt_cv_sys_global_symbol_to_import=
+  lt_cdecl_hook=
+  lt_c_name_hook=
+  lt_c_name_lib_hook=
+fi
+
 # Transform an extracted symbol line into a proper C declaration.
 # Some systems (esp. on ia64) link data and code symbols differently,
 # so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+lt_cv_sys_global_symbol_to_cdecl="sed -n"\
+$lt_cdecl_hook\
+" -e 's/^T .* \(.*\)$/extern int \1();/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'"
 
 # Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address="sed -n"\
+$lt_c_name_hook\
+" -e 's/^: \(.*\) .*$/  {\"\1\", (void *) 0},/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/  {\"\1\", (void *) \&\1},/p'"
+
+# Transform an extracted symbol line into symbol name with lib prefix and
+# symbol address.
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n"\
+$lt_c_name_lib_hook\
+" -e 's/^: \(.*\) .*$/  {\"\1\", (void *) 0},/p'"\
+" -e 's/^$symcode$symcode* .* \(lib.*\)$/  {\"\1\", (void *) \&\1},/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/  {\"lib\1\", (void *) \&\1},/p'"
 
 # Handle CRLF in mingw tool chain
 opt_cr=
@@ -7141,21 +6901,24 @@ for ac_symprfx in "" "_"; do
 
   # Write the raw and C identifiers.
   if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
+    # Fake it for dumpbin and say T for any non-static function,
+    # D for any global variable and I for any imported variable.
     # Also find C++ and __fastcall symbols from MSVC++,
     # which start with @ or ?.
     lt_cv_sys_global_symbol_pipe="$AWK '"\
 "     {last_section=section; section=\$ 3};"\
 "     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
 "     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\
+"     /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\
+"     /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\
 "     \$ 0!~/External *\|/{next};"\
 "     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
 "     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\
+"     {split(\$ 0,a,/\||\r/); split(a[2],s)};"\
+"     s[1]~/^[@?]/{print f,s[1],s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\
 "     ' prfx=^$ac_symprfx"
   else
     lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[	 ]\($symcode$symcode*\)[	 ][	 ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
@@ -7203,11 +6966,11 @@ _LT_EOF
 	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
 	  cat <<_LT_EOF > conftest.$ac_ext
 /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
+#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE
+/* DATA imports from DLLs on WIN32 can't be const, because runtime
    relocations are performed -- see ld's documentation on pseudo-relocs.  */
 # define LT_DLSYM_CONST
-#elif defined(__osf__)
+#elif defined __osf__
 /* This system does not cope well with relocations in const data.  */
 # define LT_DLSYM_CONST
 #else
@@ -7233,7 +6996,7 @@ lt__PROGRAM__LTX_preloaded_symbols[] =
 {
   { "@PROGRAM@", (void *) 0 },
 _LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  $SED "s/^$symcode$symcode* .* \(.*\)$/  {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
 	  cat <<\_LT_EOF >> conftest.$ac_ext
   {0, (void *) 0}
 };
@@ -7253,13 +7016,13 @@ _LT_EOF
 	  mv conftest.$ac_objext conftstm.$ac_objext
 	  lt_globsym_save_LIBS=$LIBS
 	  lt_globsym_save_CFLAGS=$CFLAGS
-	  LIBS="conftstm.$ac_objext"
+	  LIBS=conftstm.$ac_objext
 	  CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag"
 	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
   (eval $ac_link) 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext}; then
+  test $ac_status = 0; } && test -s conftest$ac_exeext; then
 	    pipe_works=yes
 	  fi
 	  LIBS=$lt_globsym_save_LIBS
@@ -7280,7 +7043,7 @@ _LT_EOF
   rm -rf conftest* conftst*
 
   # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
+  if test yes = "$pipe_works"; then
     break
   else
     lt_cv_sys_global_symbol_pipe=
@@ -7333,6 +7096,16 @@ fi
 
 
 
+
+
+
+
+
+
+
+
+
+
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5
 $as_echo_n "checking for sysroot... " >&6; }
 
@@ -7345,9 +7118,9 @@ fi
 
 
 lt_sysroot=
-case ${with_sysroot} in #(
+case $with_sysroot in #(
  yes)
-   if test "$GCC" = yes; then
+   if test yes = "$GCC"; then
      lt_sysroot=`$CC --print-sysroot 2>/dev/null`
    fi
    ;; #(
@@ -7357,8 +7130,8 @@ case ${with_sysroot} in #(
  no|'')
    ;; #(
  *)
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5
-$as_echo "${with_sysroot}" >&6; }
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_sysroot" >&5
+$as_echo "$with_sysroot" >&6; }
    as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5
    ;;
 esac
@@ -7370,18 +7143,99 @@ $as_echo "${lt_sysroot:-no}" >&6; }
 
 
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a working dd" >&5
+$as_echo_n "checking for a working dd... " >&6; }
+if ${ac_cv_path_lt_DD+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  printf 0123456789abcdef0123456789abcdef >conftest.i
+cat conftest.i conftest.i >conftest2.i
+: ${lt_DD:=$DD}
+if test -z "$lt_DD"; then
+  ac_path_lt_DD_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in dd; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_lt_DD="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_lt_DD" || continue
+if "$ac_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; then
+  cmp -s conftest.i conftest.out \
+  && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=:
+fi
+      $ac_path_lt_DD_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_lt_DD"; then
+    :
+  fi
+else
+  ac_cv_path_lt_DD=$lt_DD
+fi
+
+rm -f conftest.i conftest2.i conftest.out
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_lt_DD" >&5
+$as_echo "$ac_cv_path_lt_DD" >&6; }
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to truncate binary pipes" >&5
+$as_echo_n "checking how to truncate binary pipes... " >&6; }
+if ${lt_cv_truncate_bin+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  printf 0123456789abcdef0123456789abcdef >conftest.i
+cat conftest.i conftest.i >conftest2.i
+lt_cv_truncate_bin=
+if "$ac_cv_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; then
+  cmp -s conftest.i conftest.out \
+  && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1"
+fi
+rm -f conftest.i conftest2.i conftest.out
+test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_truncate_bin" >&5
+$as_echo "$lt_cv_truncate_bin" >&6; }
+
+
+
+
+
+
+
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+func_cc_basename ()
+{
+    for cc_temp in $*""; do
+      case $cc_temp in
+        compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+        distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+        \-*) ;;
+        *) break;;
+      esac
+    done
+    func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+}
+
 # Check whether --enable-libtool-lock was given.
 if test "${enable_libtool_lock+set}" = set; then :
   enableval=$enable_libtool_lock;
 fi
 
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+test no = "$enable_libtool_lock" || enable_libtool_lock=yes
 
 # Some flags need to be propagated to the compiler or linker for good
 # libtool support.
 case $host in
 ia64-*-hpux*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set mode
+  # options accordingly.
   echo 'int i;' > conftest.$ac_ext
   if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
   (eval $ac_compile) 2>&5
@@ -7390,24 +7244,25 @@ ia64-*-hpux*)
   test $ac_status = 0; }; then
     case `/usr/bin/file conftest.$ac_objext` in
       *ELF-32*)
-	HPUX_IA64_MODE="32"
+	HPUX_IA64_MODE=32
 	;;
       *ELF-64*)
-	HPUX_IA64_MODE="64"
+	HPUX_IA64_MODE=64
 	;;
     esac
   fi
   rm -rf conftest*
   ;;
 *-*-irix6*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
   echo '#line '$LINENO' "configure"' > conftest.$ac_ext
   if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
   (eval $ac_compile) 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
+    if test yes = "$lt_cv_prog_gnu_ld"; then
       case `/usr/bin/file conftest.$ac_objext` in
 	*32-bit*)
 	  LD="${LD-ld} -melf32bsmip"
@@ -7436,35 +7291,76 @@ ia64-*-hpux*)
   rm -rf conftest*
   ;;
 
-x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
-s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
+mips64*-*linux*)
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
+  echo '#line '$LINENO' "configure"' > conftest.$ac_ext
   if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
   (eval $ac_compile) 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-    case `/usr/bin/file conftest.o` in
+    emul=elf
+    case `/usr/bin/file conftest.$ac_objext` in
       *32-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_i386_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    case `/usr/bin/file conftest.o` in
-	      *x86-64*)
-		LD="${LD-ld} -m elf32_x86_64"
-		;;
-	      *)
-		LD="${LD-ld} -m elf_i386"
-		;;
+	emul="${emul}32"
+	;;
+      *64-bit*)
+	emul="${emul}64"
+	;;
+    esac
+    case `/usr/bin/file conftest.$ac_objext` in
+      *MSB*)
+	emul="${emul}btsmip"
+	;;
+      *LSB*)
+	emul="${emul}ltsmip"
+	;;
+    esac
+    case `/usr/bin/file conftest.$ac_objext` in
+      *N32*)
+	emul="${emul}n32"
+	;;
+    esac
+    LD="${LD-ld} -m $emul"
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.  Note that the listed cases only cover the
+  # situations where additional linker options are needed (such as when
+  # doing 32-bit compilation for a host where ld defaults to 64-bit, or
+  # vice versa); the common cases where no linker options are needed do
+  # not appear in the list.
+  echo 'int i;' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
+  (eval $ac_compile) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD="${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    case `/usr/bin/file conftest.o` in
+	      *x86-64*)
+		LD="${LD-ld} -m elf32_x86_64"
+		;;
+	      *)
+		LD="${LD-ld} -m elf_i386"
+		;;
 	    esac
 	    ;;
-	  powerpc64le-*)
+	  powerpc64le-*linux*)
 	    LD="${LD-ld} -m elf32lppclinux"
 	    ;;
-	  powerpc64-*)
+	  powerpc64-*linux*)
 	    LD="${LD-ld} -m elf32ppclinux"
 	    ;;
 	  s390x-*linux*)
@@ -7483,10 +7379,10 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 	  x86_64-*linux*)
 	    LD="${LD-ld} -m elf_x86_64"
 	    ;;
-	  powerpcle-*)
+	  powerpcle-*linux*)
 	    LD="${LD-ld} -m elf64lppc"
 	    ;;
-	  powerpc-*)
+	  powerpc-*linux*)
 	    LD="${LD-ld} -m elf64ppc"
 	    ;;
 	  s390*-*linux*|s390*-*tpf*)
@@ -7504,7 +7400,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 
 *-*-sco3.2v5*)
   # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
+  SAVE_CFLAGS=$CFLAGS
   CFLAGS="$CFLAGS -belf"
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5
 $as_echo_n "checking whether the C compiler needs -belf... " >&6; }
@@ -7544,13 +7440,14 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5
 $as_echo "$lt_cv_cc_needs_belf" >&6; }
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+  if test yes != "$lt_cv_cc_needs_belf"; then
     # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
+    CFLAGS=$SAVE_CFLAGS
   fi
   ;;
 *-*solaris*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
   echo 'int i;' > conftest.$ac_ext
   if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
   (eval $ac_compile) 2>&5
@@ -7562,7 +7459,7 @@ $as_echo "$lt_cv_cc_needs_belf" >&6; }
       case $lt_cv_prog_gnu_ld in
       yes*)
         case $host in
-        i?86-*-solaris*)
+        i?86-*-solaris*|x86_64-*-solaris*)
           LD="${LD-ld} -m elf_x86_64"
           ;;
         sparc*-*-solaris*)
@@ -7571,7 +7468,7 @@ $as_echo "$lt_cv_cc_needs_belf" >&6; }
         esac
         # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
         if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
-          LD="${LD-ld}_sol2"
+          LD=${LD-ld}_sol2
         fi
         ;;
       *)
@@ -7587,7 +7484,7 @@ $as_echo "$lt_cv_cc_needs_belf" >&6; }
   ;;
 esac
 
-need_locks="$enable_libtool_lock"
+need_locks=$enable_libtool_lock
 
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args.
@@ -7698,7 +7595,7 @@ else
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5
 $as_echo "$lt_cv_path_mainfest_tool" >&6; }
-if test "x$lt_cv_path_mainfest_tool" != xyes; then
+if test yes != "$lt_cv_path_mainfest_tool"; then
   MANIFEST_TOOL=:
 fi
 
@@ -8201,7 +8098,7 @@ if ${lt_cv_apple_cc_single_mod+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
+      if test -z "$LT_MULTI_MODULE"; then
 	# By default we will add the -single_module flag. You can override
 	# by either setting the environment variable LT_MULTI_MODULE
 	# non-empty at configure time, or by adding -multi_module to the
@@ -8219,7 +8116,7 @@ else
 	  cat conftest.err >&5
 	# Otherwise, if the output was created with a 0 exit code from
 	# the compiler, it worked.
-	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	elif test -f libconftest.dylib && test 0 = "$_lt_result"; then
 	  lt_cv_apple_cc_single_mod=yes
 	else
 	  cat conftest.err >&5
@@ -8258,7 +8155,7 @@ else
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
-	LDFLAGS="$save_LDFLAGS"
+	LDFLAGS=$save_LDFLAGS
 
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5
@@ -8287,7 +8184,7 @@ _LT_EOF
       _lt_result=$?
       if test -s conftest.err && $GREP force_load conftest.err; then
 	cat conftest.err >&5
-      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+      elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then
 	lt_cv_ld_force_load=yes
       else
 	cat conftest.err >&5
@@ -8300,32 +8197,32 @@ fi
 $as_echo "$lt_cv_ld_force_load" >&6; }
     case $host_os in
     rhapsody* | darwin1.[012])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+      _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;;
     darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+      _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;;
     darwin*) # darwin 5.x on
       # if running on 10.5 or later, the deployment target defaults
       # to the OS version, if on x86, and 10.4, the deployment
       # target defaults to 10.4. Don't you love it?
       case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
 	10.0,*86*-darwin8*|10.0,*-darwin[91]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[012]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	  _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;;
+	10.[012][,.]*)
+	  _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;;
 	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	  _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;;
       esac
     ;;
   esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+    if test yes = "$lt_cv_apple_cc_single_mod"; then
       _lt_dar_single_mod='$single_module'
     fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    if test yes = "$lt_cv_ld_exported_symbols_list"; then
+      _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym'
     else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib'
     fi
-    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+    if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then
       _lt_dsymutil='~$DSYMUTIL $lib || :'
     else
       _lt_dsymutil=
@@ -8333,6 +8230,178 @@ $as_echo "$lt_cv_ld_force_load" >&6; }
     ;;
   esac
 
+# func_munge_path_list VARIABLE PATH
+# -----------------------------------
+# VARIABLE is name of variable containing _space_ separated list of
+# directories to be munged by the contents of PATH, which is string
+# having a format:
+# "DIR[:DIR]:"
+#       string "DIR[ DIR]" will be prepended to VARIABLE
+# ":DIR[:DIR]"
+#       string "DIR[ DIR]" will be appended to VARIABLE
+# "DIRP[:DIRP]::[DIRA:]DIRA"
+#       string "DIRP[ DIRP]" will be prepended to VARIABLE and string
+#       "DIRA[ DIRA]" will be appended to VARIABLE
+# "DIR[:DIR]"
+#       VARIABLE will be replaced by "DIR[ DIR]"
+func_munge_path_list ()
+{
+    case x$2 in
+    x)
+        ;;
+    *:)
+        eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\"
+        ;;
+    x:*)
+        eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\"
+        ;;
+    *::*)
+        eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\"
+        eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\"
+        ;;
+    *)
+        eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\"
+        ;;
+    esac
+}
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
+fi
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
 $as_echo_n "checking for ANSI C header files... " >&6; }
@@ -8499,14 +8568,14 @@ if test "${enable_shared+set}" = set; then :
     *)
       enable_shared=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_shared=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac
 else
@@ -8530,14 +8599,14 @@ if test "${enable_static+set}" = set; then :
     *)
      enable_static=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_static=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac
 else
@@ -8561,14 +8630,14 @@ if test "${with_pic+set}" = set; then :
     *)
       pic_mode=default
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for lt_pkg in $withval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$lt_pkg" = "X$lt_p"; then
 	  pic_mode=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac
 else
@@ -8576,8 +8645,6 @@ else
 fi
 
 
-test -z "$pic_mode" && pic_mode=default
-
 
 
 
@@ -8593,14 +8660,14 @@ if test "${enable_fast_install+set}" = set; then :
     *)
       enable_fast_install=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_fast_install=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac
 else
@@ -8614,11 +8681,63 @@ fi
 
 
 
+  shared_archive_member_spec=
+case $host,$enable_shared in
+power*-*-aix[5-9]*,yes)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking which variant of shared library versioning to provide" >&5
+$as_echo_n "checking which variant of shared library versioning to provide... " >&6; }
+
+# Check whether --with-aix-soname was given.
+if test "${with_aix_soname+set}" = set; then :
+  withval=$with_aix_soname; case $withval in
+    aix|svr4|both)
+      ;;
+    *)
+      as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5
+      ;;
+    esac
+    lt_cv_with_aix_soname=$with_aix_soname
+else
+  if ${lt_cv_with_aix_soname+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_with_aix_soname=aix
+fi
+
+    with_aix_soname=$lt_cv_with_aix_soname
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_aix_soname" >&5
+$as_echo "$with_aix_soname" >&6; }
+  if test aix != "$with_aix_soname"; then
+    # For the AIX way of multilib, we name the shared archive member
+    # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o',
+    # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File.
+    # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag,
+    # the AIX toolchain works better with OBJECT_MODE set (default 32).
+    if test 64 = "${OBJECT_MODE-32}"; then
+      shared_archive_member_spec=shr_64
+    else
+      shared_archive_member_spec=shr
+    fi
+  fi
+  ;;
+*)
+  with_aix_soname=aix
+  ;;
+esac
+
+
+
+
+
+
+
 
 
 
 # This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
+LIBTOOL_DEPS=$ltmain
 
 # Always use our own libtool.
 LIBTOOL='$(SHELL) $(top_builddir)/libtool'
@@ -8667,7 +8786,7 @@ test -z "$LN_S" && LN_S="ln -s"
 
 
 
-if test -n "${ZSH_VERSION+set}" ; then
+if test -n "${ZSH_VERSION+set}"; then
    setopt NO_GLOB_SUBST
 fi
 
@@ -8706,7 +8825,7 @@ aix3*)
   # AIX sometimes has problems with the GCC collect2 program.  For some
   # reason, if we set the COLLECT_NAMES environment variable, the problems
   # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
+  if test set != "${COLLECT_NAMES+set}"; then
     COLLECT_NAMES=
     export COLLECT_NAMES
   fi
@@ -8717,14 +8836,14 @@ esac
 ofile=libtool
 can_build_shared=yes
 
-# All known linkers require a `.a' archive for static linking (except MSVC,
+# All known linkers require a '.a' archive for static linking (except MSVC,
 # which needs '.lib').
 libext=a
 
-with_gnu_ld="$lt_cv_prog_gnu_ld"
+with_gnu_ld=$lt_cv_prog_gnu_ld
 
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
+old_CC=$CC
+old_CFLAGS=$CFLAGS
 
 # Set sane defaults for various variables
 test -z "$CC" && CC=cc
@@ -8733,15 +8852,8 @@ test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
 test -z "$LD" && LD=ld
 test -z "$ac_objext" && ac_objext=o
 
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+func_cc_basename $compiler
+cc_basename=$func_cc_basename_result
 
 
 # Only perform the check for file, if the check method requires it
@@ -8756,22 +8868,22 @@ if ${lt_cv_path_MAGIC_CMD+:} false; then :
 else
   case $MAGIC_CMD in
 [\\/*] |  ?:[\\/]*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path.
   ;;
 *)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  lt_save_MAGIC_CMD=$MAGIC_CMD
+  lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
   ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
   for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
     test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/${ac_tool_prefix}file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file"
+    if test -f "$ac_dir/${ac_tool_prefix}file"; then
+      lt_cv_path_MAGIC_CMD=$ac_dir/"${ac_tool_prefix}file"
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
 	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
 	    :
@@ -8794,13 +8906,13 @@ _LT_EOF
       break
     fi
   done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  IFS=$lt_save_ifs
+  MAGIC_CMD=$lt_save_MAGIC_CMD
   ;;
 esac
 fi
 
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 if test -n "$MAGIC_CMD"; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
 $as_echo "$MAGIC_CMD" >&6; }
@@ -8822,22 +8934,22 @@ if ${lt_cv_path_MAGIC_CMD+:} false; then :
 else
   case $MAGIC_CMD in
 [\\/*] |  ?:[\\/]*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path.
   ;;
 *)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  lt_save_MAGIC_CMD=$MAGIC_CMD
+  lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
   ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
   for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
     test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/file"
+    if test -f "$ac_dir/file"; then
+      lt_cv_path_MAGIC_CMD=$ac_dir/"file"
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
 	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
 	    :
@@ -8860,13 +8972,13 @@ _LT_EOF
       break
     fi
   done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  IFS=$lt_save_ifs
+  MAGIC_CMD=$lt_save_MAGIC_CMD
   ;;
 esac
 fi
 
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 if test -n "$MAGIC_CMD"; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
 $as_echo "$MAGIC_CMD" >&6; }
@@ -8887,7 +8999,7 @@ esac
 
 # Use C for the default configuration in the libtool script
 
-lt_save_CC="$CC"
+lt_save_CC=$CC
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -8949,7 +9061,7 @@ if test -n "$compiler"; then
 
 lt_prog_compiler_no_builtin_flag=
 
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   case $cc_basename in
   nvcc*)
     lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;;
@@ -8965,7 +9077,7 @@ else
   lt_cv_prog_compiler_rtti_exceptions=no
    ac_outfile=conftest.$ac_objext
    echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="-fno-rtti -fno-exceptions"
+   lt_compiler_flag="-fno-rtti -fno-exceptions"  ## exclude from sc_useless_quotes_in_assignment
    # Insert the option either (1) after the last *FLAGS variable, or
    # (2) before a word containing "conftest.", or (3) at the end.
    # Note that $ac_compile itself does not contain backslashes and begins
@@ -8995,7 +9107,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; }
 
-if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
+if test yes = "$lt_cv_prog_compiler_rtti_exceptions"; then
     lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions"
 else
     :
@@ -9013,17 +9125,18 @@ lt_prog_compiler_pic=
 lt_prog_compiler_static=
 
 
-  if test "$GCC" = yes; then
+  if test yes = "$GCC"; then
     lt_prog_compiler_wl='-Wl,'
     lt_prog_compiler_static='-static'
 
     case $host_os in
       aix*)
       # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# AIX 5 now supports IA64 processor
 	lt_prog_compiler_static='-Bstatic'
       fi
+      lt_prog_compiler_pic='-fPIC'
       ;;
 
     amigaos*)
@@ -9034,8 +9147,8 @@ lt_prog_compiler_static=
         ;;
       m68k)
             # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
+            # adding the '-m68020' flag to GCC prevents building anything better,
+            # like '-m68040'.
             lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4'
         ;;
       esac
@@ -9051,6 +9164,11 @@ lt_prog_compiler_static=
       # Although the cygwin gcc ignores -fPIC, still need this for old-style
       # (--disable-auto-import) libraries
       lt_prog_compiler_pic='-DDLL_EXPORT'
+      case $host_os in
+      os2*)
+	lt_prog_compiler_static='$wl-static'
+	;;
+      esac
       ;;
 
     darwin* | rhapsody*)
@@ -9121,7 +9239,7 @@ lt_prog_compiler_static=
     case $host_os in
     aix*)
       lt_prog_compiler_wl='-Wl,'
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# AIX 5 now supports IA64 processor
 	lt_prog_compiler_static='-Bstatic'
       else
@@ -9129,10 +9247,29 @@ lt_prog_compiler_static=
       fi
       ;;
 
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      lt_prog_compiler_pic='-fno-common'
+      case $cc_basename in
+      nagfor*)
+        # NAG Fortran compiler
+        lt_prog_compiler_wl='-Wl,-Wl,,'
+        lt_prog_compiler_pic='-PIC'
+        lt_prog_compiler_static='-Bstatic'
+        ;;
+      esac
+      ;;
+
     mingw* | cygwin* | pw32* | os2* | cegcc*)
       # This hack is so that the source file can tell whether it is being
       # built for inclusion in a dll (and should export symbols for example).
       lt_prog_compiler_pic='-DDLL_EXPORT'
+      case $host_os in
+      os2*)
+	lt_prog_compiler_static='$wl-static'
+	;;
+      esac
       ;;
 
     hpux9* | hpux10* | hpux11*)
@@ -9148,7 +9285,7 @@ lt_prog_compiler_static=
 	;;
       esac
       # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      lt_prog_compiler_static='${wl}-a ${wl}archive'
+      lt_prog_compiler_static='$wl-a ${wl}archive'
       ;;
 
     irix5* | irix6* | nonstopux*)
@@ -9159,7 +9296,7 @@ lt_prog_compiler_static=
 
     linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
       case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
+      # old Intel for x86_64, which still supported -KPIC.
       ecc*)
 	lt_prog_compiler_wl='-Wl,'
 	lt_prog_compiler_pic='-KPIC'
@@ -9184,6 +9321,12 @@ lt_prog_compiler_static=
 	lt_prog_compiler_pic='-PIC'
 	lt_prog_compiler_static='-Bstatic'
 	;;
+      tcc*)
+	# Fabrice Bellard et al's Tiny C Compiler
+	lt_prog_compiler_wl='-Wl,'
+	lt_prog_compiler_pic='-fPIC'
+	lt_prog_compiler_static='-static'
+	;;
       pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
@@ -9281,7 +9424,7 @@ lt_prog_compiler_static=
       ;;
 
     sysv4*MP*)
-      if test -d /usr/nec ;then
+      if test -d /usr/nec; then
 	lt_prog_compiler_pic='-Kconform_pic'
 	lt_prog_compiler_static='-Bstatic'
       fi
@@ -9310,7 +9453,7 @@ lt_prog_compiler_static=
   fi
 
 case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
+  # For platforms that do not support PIC, -DPIC is meaningless:
   *djgpp*)
     lt_prog_compiler_pic=
     ;;
@@ -9342,7 +9485,7 @@ else
   lt_cv_prog_compiler_pic_works=no
    ac_outfile=conftest.$ac_objext
    echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$lt_prog_compiler_pic -DPIC"
+   lt_compiler_flag="$lt_prog_compiler_pic -DPIC"  ## exclude from sc_useless_quotes_in_assignment
    # Insert the option either (1) after the last *FLAGS variable, or
    # (2) before a word containing "conftest.", or (3) at the end.
    # Note that $ac_compile itself does not contain backslashes and begins
@@ -9372,7 +9515,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5
 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; }
 
-if test x"$lt_cv_prog_compiler_pic_works" = xyes; then
+if test yes = "$lt_cv_prog_compiler_pic_works"; then
     case $lt_prog_compiler_pic in
      "" | " "*) ;;
      *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;;
@@ -9404,7 +9547,7 @@ if ${lt_cv_prog_compiler_static_works+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   lt_cv_prog_compiler_static_works=no
-   save_LDFLAGS="$LDFLAGS"
+   save_LDFLAGS=$LDFLAGS
    LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
    echo "$lt_simple_link_test_code" > conftest.$ac_ext
    if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
@@ -9423,13 +9566,13 @@ else
      fi
    fi
    $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
+   LDFLAGS=$save_LDFLAGS
 
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5
 $as_echo "$lt_cv_prog_compiler_static_works" >&6; }
 
-if test x"$lt_cv_prog_compiler_static_works" = xyes; then
+if test yes = "$lt_cv_prog_compiler_static_works"; then
     :
 else
     lt_prog_compiler_static=
@@ -9549,8 +9692,8 @@ $as_echo "$lt_cv_prog_compiler_c_o" >&6; }
 
 
 
-hard_links="nottested"
-if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then
+hard_links=nottested
+if test no = "$lt_cv_prog_compiler_c_o" && test no != "$need_locks"; then
   # do not overwrite the value of need_locks provided by the user
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5
 $as_echo_n "checking if we can lock with hard links... " >&6; }
@@ -9562,9 +9705,9 @@ $as_echo_n "checking if we can lock with hard links... " >&6; }
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5
 $as_echo "$hard_links" >&6; }
-  if test "$hard_links" = no; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
-$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
+  if test no = "$hard_links"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&5
+$as_echo "$as_me: WARNING: '$CC' does not support '-c -o', so 'make -j' may be unsafe" >&2;}
     need_locks=warn
   fi
 else
@@ -9607,9 +9750,9 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
   # included in the symbol list
   include_expsyms=
   # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
+  # it will be wrapped by ' (' and ')$', so one must not match beginning or
+  # end of line.  Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc',
+  # as well as any symbol that contains 'd'.
   exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'
   # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
   # platforms (ab)use it in PIC code, but their linkers get confused if
@@ -9624,7 +9767,7 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
     # FIXME: the MSVC++ port hasn't been tested in a loooong time
     # When not using gcc, we currently assume that we are using
     # Microsoft Visual C++.
-    if test "$GCC" != yes; then
+    if test yes != "$GCC"; then
       with_gnu_ld=no
     fi
     ;;
@@ -9632,7 +9775,7 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
     # we just hope/assume this is gcc and not c89 (= MSVC++)
     with_gnu_ld=yes
     ;;
-  openbsd*)
+  openbsd* | bitrig*)
     with_gnu_ld=no
     ;;
   linux* | k*bsd*-gnu | gnu*)
@@ -9645,7 +9788,7 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
   # On some targets, GNU ld is compatible enough with the native linker
   # that we're better off using the native interface for both.
   lt_use_gnu_ld_interface=no
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     case $host_os in
       aix*)
 	# The AIX port of GNU ld has always aspired to compatibility
@@ -9667,24 +9810,24 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
     esac
   fi
 
-  if test "$lt_use_gnu_ld_interface" = yes; then
+  if test yes = "$lt_use_gnu_ld_interface"; then
     # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
+    wlarc='$wl'
 
     # Set some defaults for GNU ld with shared library support. These
     # are reset later if shared libraries are not supported. Putting them
     # here allows them to be overridden if necessary.
     runpath_var=LD_RUN_PATH
-    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-    export_dynamic_flag_spec='${wl}--export-dynamic'
+    hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
+    export_dynamic_flag_spec='$wl--export-dynamic'
     # ancient GNU ld didn't support --whole-archive et. al.
     if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      whole_archive_flag_spec=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive'
     else
       whole_archive_flag_spec=
     fi
     supports_anon_versioning=no
-    case `$LD -v 2>&1` in
+    case `$LD -v | $SED -e 's/(^)\+)\s\+//' 2>&1` in
       *GNU\ gold*) supports_anon_versioning=yes ;;
       *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
       *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
@@ -9697,7 +9840,7 @@ $as_echo_n "checking whether the $compiler linker ($LD) supports shared librarie
     case $host_os in
     aix[3-9]*)
       # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
+      if test ia64 != "$host_cpu"; then
 	ld_shlibs=no
 	cat <<_LT_EOF 1>&2
 
@@ -9716,7 +9859,7 @@ _LT_EOF
       case $host_cpu in
       powerpc)
             # see comment about AmigaOS4 .so support
-            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
             archive_expsym_cmds=''
         ;;
       m68k)
@@ -9732,7 +9875,7 @@ _LT_EOF
 	allow_undefined_flag=unsupported
 	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
 	# support --undefined.  This deserves some investigation.  FIXME
-	archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
       else
 	ld_shlibs=no
       fi
@@ -9742,7 +9885,7 @@ _LT_EOF
       # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
       # as there is no search path for DLLs.
       hardcode_libdir_flag_spec='-L$libdir'
-      export_dynamic_flag_spec='${wl}--export-all-symbols'
+      export_dynamic_flag_spec='$wl--export-all-symbols'
       allow_undefined_flag=unsupported
       always_export_symbols=no
       enable_shared_with_static_runtimes=yes
@@ -9750,61 +9893,89 @@ _LT_EOF
       exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'
 
       if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file, use it as
+	# is; otherwise, prepend EXPORTS...
+	archive_expsym_cmds='if   test DEF = "`$SED -n     -e '\''s/^[	 ]*//'\''     -e '\''/^\(;.*\)*$/d'\''     -e '\''s/^\(EXPORTS\|LIBRARY\)\([	 ].*\)*$/DEF/p'\''     -e q     $export_symbols`" ; then
+          cp $export_symbols $output_objdir/$soname.def;
+        else
+          echo EXPORTS > $output_objdir/$soname.def;
+          cat $export_symbols >> $output_objdir/$soname.def;
+        fi~
+        $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
       else
 	ld_shlibs=no
       fi
       ;;
 
     haiku*)
-      archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
       link_all_deplibs=yes
       ;;
 
+    os2*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_minus_L=yes
+      allow_undefined_flag=unsupported
+      shrext_cmds=.dll
+      archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	prefix_cmds="$SED"~
+	if test EXPORTS = "`$SED 1q $export_symbols`"; then
+	  prefix_cmds="$prefix_cmds -e 1d";
+	fi~
+	prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~
+	cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def'
+      enable_shared_with_static_runtimes=yes
+      ;;
+
     interix[3-9]*)
       hardcode_direct=no
       hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-      export_dynamic_flag_spec='${wl}-E'
+      hardcode_libdir_flag_spec='$wl-rpath,$libdir'
+      export_dynamic_flag_spec='$wl-E'
       # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
       # Instead, shared libraries are loaded at an image base (0x10000000 by
       # default) and relocated if they conflict, which is a slow very memory
       # consuming and fragmenting process.  To avoid this, we pick a random,
       # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
       # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      archive_expsym_cmds='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
       ;;
 
     gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
       tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
+      if test linux-dietlibc = "$host_os"; then
 	case $cc_basename in
 	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
 	esac
       fi
       if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
+	 && test no = "$tmp_diet"
       then
 	tmp_addflag=' $pic_flag'
 	tmp_sharedflag='-shared'
 	case $cc_basename,$host_cpu in
         pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  tmp_addflag=' $pic_flag'
 	  ;;
 	pgf77* | pgf90* | pgf95* | pgfortran*)
 					# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  tmp_addflag=' $pic_flag -Mnomain' ;;
 	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
 	  tmp_addflag=' -i_dynamic' ;;
@@ -9815,42 +9986,47 @@ _LT_EOF
 	lf95*)				# Lahey Fortran 8.1
 	  whole_archive_flag_spec=
 	  tmp_sharedflag='--shared' ;;
+        nagfor*)                        # NAGFOR 5.3
+          tmp_sharedflag='-Wl,-shared' ;;
 	xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below)
 	  tmp_sharedflag='-qmkshrobj'
 	  tmp_addflag= ;;
 	nvcc*)	# Cuda Compiler Driver 2.2
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  whole_archive_flag_spec='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  compiler_needs_object=yes
 	  ;;
 	esac
 	case `$CC -V 2>&1 | sed 5q` in
 	*Sun\ C*)			# Sun C 5.9
-	  whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  whole_archive_flag_spec='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  compiler_needs_object=yes
 	  tmp_sharedflag='-G' ;;
 	*Sun\ F*)			# Sun Fortran 8.3
 	  tmp_sharedflag='-G' ;;
 	esac
-	archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
 
-        if test "x$supports_anon_versioning" = xyes; then
+        if test yes = "$supports_anon_versioning"; then
           archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
-	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	    echo "local: *; };" >> $output_objdir/$libname.ver~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+            cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+            echo "local: *; };" >> $output_objdir/$libname.ver~
+            $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib'
         fi
 
 	case $cc_basename in
+	tcc*)
+	  export_dynamic_flag_spec='-rdynamic'
+	  ;;
 	xlf* | bgf* | bgxlf* | mpixlf*)
 	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
 	  whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive'
-	  hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+	  hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
 	  archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
-	  if test "x$supports_anon_versioning" = xyes; then
+	  if test yes = "$supports_anon_versioning"; then
 	    archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
-	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+              cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+              echo "local: *; };" >> $output_objdir/$libname.ver~
+              $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
 	  fi
 	  ;;
 	esac
@@ -9864,8 +10040,8 @@ _LT_EOF
 	archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
 	wlarc=
       else
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       fi
       ;;
 
@@ -9883,8 +10059,8 @@ _LT_EOF
 
 _LT_EOF
       elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	ld_shlibs=no
       fi
@@ -9896,7 +10072,7 @@ _LT_EOF
 	ld_shlibs=no
 	cat <<_LT_EOF 1>&2
 
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot
 *** reliably create shared libraries on SCO systems.  Therefore, libtool
 *** is disabling shared libraries support.  We urge you to upgrade GNU
 *** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
@@ -9911,9 +10087,9 @@ _LT_EOF
 	  # DT_RUNPATH tag from executables and libraries.  But doing so
 	  # requires that you compile everything twice, which is a pain.
 	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-	    archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	    hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
+	    archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	    archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 	  else
 	    ld_shlibs=no
 	  fi
@@ -9930,15 +10106,15 @@ _LT_EOF
 
     *)
       if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	ld_shlibs=no
       fi
       ;;
     esac
 
-    if test "$ld_shlibs" = no; then
+    if test no = "$ld_shlibs"; then
       runpath_var=
       hardcode_libdir_flag_spec=
       export_dynamic_flag_spec=
@@ -9954,7 +10130,7 @@ _LT_EOF
       # Note: this linker hardcodes the directories in LIBPATH if there
       # are no directories specified by -L.
       hardcode_minus_L=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+      if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then
 	# Neither direct hardcoding nor static linking is supported with a
 	# broken collect2.
 	hardcode_direct=unsupported
@@ -9962,34 +10138,57 @@ _LT_EOF
       ;;
 
     aix[4-9]*)
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# On IA64, the linker does run time linking by default, so we don't
 	# have to do anything special.
 	aix_use_runtimelinking=no
 	exp_sym_flag='-Bexport'
-	no_entry_flag=""
+	no_entry_flag=
       else
 	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	# Also, AIX nm treats weak defined symbols like other global
-	# defined symbols, whereas GNU nm marks them as "W".
+	# -C means demangle to GNU nm, but means don't demangle to AIX nm.
+	# Without the "-l" option, or with the "-B" option, AIX nm treats
+	# weak defined symbols like other global defined symbols, whereas
+	# GNU nm marks them as "W".
+	# While the 'weak' keyword is ignored in the Export File, we need
+	# it in the Import File for the 'aix-soname' feature, so we have
+	# to replace the "-B" option with "-P" for AIX nm.
 	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	  export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols'
 	else
-	  export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	  export_symbols_cmds='`func_echo_all $NM | $SED -e '\''s/B\([^B]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && (substr(\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols'
 	fi
 	aix_use_runtimelinking=no
 
 	# Test if we are trying to use run time linking or normal
 	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
+	# have runtime linking enabled, and use it for executables.
+	# For shared libraries, we enable/disable runtime linking
+	# depending on the kind of the shared library created -
+	# when "with_aix_soname,aix_use_runtimelinking" is:
+	# "aix,no"   lib.a(lib.so.V) shared, rtl:no,  for executables
+	# "aix,yes"  lib.so          shared, rtl:yes, for executables
+	#            lib.a           static archive
+	# "both,no"  lib.so.V(shr.o) shared, rtl:yes
+	#            lib.a(lib.so.V) shared, rtl:no,  for executables
+	# "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables
+	#            lib.a(lib.so.V) shared, rtl:no
+	# "svr4,*"   lib.so.V(shr.o) shared, rtl:yes, for executables
+	#            lib.a           static archive
 	case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
 	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	  if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then
 	    aix_use_runtimelinking=yes
 	    break
 	  fi
 	  done
+	  if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then
+	    # With aix-soname=svr4, we create the lib.so.V shared archives only,
+	    # so we don't have lib.a shared libs to link our executables.
+	    # We have to force runtime linking in this case.
+	    aix_use_runtimelinking=yes
+	    LDFLAGS="$LDFLAGS -Wl,-brtl"
+	  fi
 	  ;;
 	esac
 
@@ -10008,13 +10207,21 @@ _LT_EOF
       hardcode_direct_absolute=yes
       hardcode_libdir_separator=':'
       link_all_deplibs=yes
-      file_list_spec='${wl}-f,'
-
-      if test "$GCC" = yes; then
+      file_list_spec='$wl-f,'
+      case $with_aix_soname,$aix_use_runtimelinking in
+      aix,*) ;; # traditional, no import file
+      svr4,* | *,yes) # use import file
+	# The Import File defines what to hardcode.
+	hardcode_direct=no
+	hardcode_direct_absolute=no
+	;;
+      esac
+
+      if test yes = "$GCC"; then
 	case $host_os in aix4.[012]|aix4.[012].*)
 	# We only want to do this on AIX 4.2 and lower, the check
 	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
+	  collect2name=`$CC -print-prog-name=collect2`
 	  if test -f "$collect2name" &&
 	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
 	  then
@@ -10033,36 +10240,42 @@ _LT_EOF
 	  ;;
 	esac
 	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
+	if test yes = "$aix_use_runtimelinking"; then
+	  shared_flag="$shared_flag "'$wl-G'
 	fi
-	link_all_deplibs=no
+	# Need to ensure runtime linking is disabled for the traditional
+	# shared library, or the linker may eventually find shared libraries
+	# /with/ Import File - we do not want to mix them.
+	shared_flag_aix='-shared'
+	shared_flag_svr4='-shared $wl-G'
       else
 	# not using gcc
-	if test "$host_cpu" = ia64; then
+	if test ia64 = "$host_cpu"; then
 	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
 	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
 	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
+	  if test yes = "$aix_use_runtimelinking"; then
+	    shared_flag='$wl-G'
 	  else
-	    shared_flag='${wl}-bM:SRE'
+	    shared_flag='$wl-bM:SRE'
 	  fi
+	  shared_flag_aix='$wl-bM:SRE'
+	  shared_flag_svr4='$wl-G'
 	fi
       fi
 
-      export_dynamic_flag_spec='${wl}-bexpall'
+      export_dynamic_flag_spec='$wl-bexpall'
       # It seems that -bexpall does not export symbols beginning with
       # underscore (_), so it is better to generate a list of symbols to export.
       always_export_symbols=yes
-      if test "$aix_use_runtimelinking" = yes; then
+      if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then
 	# Warning - without using the other runtime loading flags (-brtl),
 	# -berok will link without error, but may produce a broken library.
 	allow_undefined_flag='-berok'
         # Determine the default libpath from the value encoded in an
         # empty executable.
-        if test "${lt_cv_aix_libpath+set}" = set; then
+        if test set = "${lt_cv_aix_libpath+set}"; then
   aix_libpath=$lt_cv_aix_libpath
 else
   if ${lt_cv_aix_libpath_+:} false; then :
@@ -10097,7 +10310,7 @@ fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
   if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_="/usr/lib:/lib"
+    lt_cv_aix_libpath_=/usr/lib:/lib
   fi
 
 fi
@@ -10105,17 +10318,17 @@ fi
   aix_libpath=$lt_cv_aix_libpath_
 fi
 
-        hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
-        archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath"
+        archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag
       else
-	if test "$host_cpu" = ia64; then
-	  hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
+	if test ia64 = "$host_cpu"; then
+	  hardcode_libdir_flag_spec='$wl-R $libdir:/usr/lib:/lib'
 	  allow_undefined_flag="-z nodefs"
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols"
 	else
 	 # Determine the default libpath from the value encoded in an
 	 # empty executable.
-	 if test "${lt_cv_aix_libpath+set}" = set; then
+	 if test set = "${lt_cv_aix_libpath+set}"; then
   aix_libpath=$lt_cv_aix_libpath
 else
   if ${lt_cv_aix_libpath_+:} false; then :
@@ -10150,7 +10363,7 @@ fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
   if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_="/usr/lib:/lib"
+    lt_cv_aix_libpath_=/usr/lib:/lib
   fi
 
 fi
@@ -10158,21 +10371,33 @@ fi
   aix_libpath=$lt_cv_aix_libpath_
 fi
 
-	 hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+	 hardcode_libdir_flag_spec='$wl-blibpath:$libdir:'"$aix_libpath"
 	  # Warning - without using the other run time loading flags,
 	  # -berok will link without error, but may produce a broken library.
-	  no_undefined_flag=' ${wl}-bernotok'
-	  allow_undefined_flag=' ${wl}-berok'
-	  if test "$with_gnu_ld" = yes; then
+	  no_undefined_flag=' $wl-bernotok'
+	  allow_undefined_flag=' $wl-berok'
+	  if test yes = "$with_gnu_ld"; then
 	    # We only use this code for GNU lds that support --whole-archive.
-	    whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    whole_archive_flag_spec='$wl--whole-archive$convenience $wl--no-whole-archive'
 	  else
 	    # Exported symbols can be pulled into shared objects from archives
 	    whole_archive_flag_spec='$convenience'
 	  fi
 	  archive_cmds_need_lc=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	  archive_expsym_cmds='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d'
+	  # -brtl affects multiple linker settings, -berok does not and is overridden later
+	  compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([, ]\\)%-berok\\1%g"`'
+	  if test svr4 != "$with_aix_soname"; then
+	    # This is similar to how AIX traditionally builds its shared libraries.
+	    archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname'
+	  fi
+	  if test aix != "$with_aix_soname"; then
+	    archive_expsym_cmds="$archive_expsym_cmds"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 32"; fi; cat $export_symbols ) >  [...]
+	  else
+	    # used by -dlpreopen to get the symbols
+	    archive_expsym_cmds="$archive_expsym_cmds"'~$MV  $output_objdir/$realname.d/$soname $output_objdir'
+	  fi
+	  archive_expsym_cmds="$archive_expsym_cmds"'~$RM -r $output_objdir/$realname.d'
 	fi
       fi
       ;;
@@ -10181,7 +10406,7 @@ fi
       case $host_cpu in
       powerpc)
             # see comment about AmigaOS4 .so support
-            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
             archive_expsym_cmds=''
         ;;
       m68k)
@@ -10211,16 +10436,17 @@ fi
 	# Tell ltmain to make .lib files, not .a files.
 	libext=lib
 	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
+	shrext_cmds=.dll
 	# FIXME: Setting linknames here is a bad hack.
-	archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	  else
-	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	  fi~
-	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	  linknames='
+	archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames='
+	archive_expsym_cmds='if   test DEF = "`$SED -n     -e '\''s/^[	 ]*//'\''     -e '\''/^\(;.*\)*$/d'\''     -e '\''s/^\(EXPORTS\|LIBRARY\)\([	 ].*\)*$/DEF/p'\''     -e q     $export_symbols`" ; then
+            cp "$export_symbols" "$output_objdir/$soname.def";
+            echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp";
+          else
+            $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp;
+          fi~
+          $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+          linknames='
 	# The linker will not automatically build a static lib if we build a DLL.
 	# _LT_TAGVAR(old_archive_from_new_cmds, )='true'
 	enable_shared_with_static_runtimes=yes
@@ -10229,18 +10455,18 @@ fi
 	# Don't use ranlib
 	old_postinstall_cmds='chmod 644 $oldlib'
 	postlink_cmds='lt_outputfile="@OUTPUT@"~
-	  lt_tool_outputfile="@TOOL_OUTPUT@"~
-	  case $lt_outputfile in
-	    *.exe|*.EXE) ;;
-	    *)
-	      lt_outputfile="$lt_outputfile.exe"
-	      lt_tool_outputfile="$lt_tool_outputfile.exe"
-	      ;;
-	  esac~
-	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	    $RM "$lt_outputfile.manifest";
-	  fi'
+          lt_tool_outputfile="@TOOL_OUTPUT@"~
+          case $lt_outputfile in
+            *.exe|*.EXE) ;;
+            *)
+              lt_outputfile=$lt_outputfile.exe
+              lt_tool_outputfile=$lt_tool_outputfile.exe
+              ;;
+          esac~
+          if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then
+            $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+            $RM "$lt_outputfile.manifest";
+          fi'
 	;;
       *)
 	# Assume MSVC wrapper
@@ -10249,7 +10475,7 @@ fi
 	# Tell ltmain to make .lib files, not .a files.
 	libext=lib
 	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
+	shrext_cmds=.dll
 	# FIXME: Setting linknames here is a bad hack.
 	archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
 	# The linker will automatically build a .lib file if we build a DLL.
@@ -10268,24 +10494,24 @@ fi
   hardcode_direct=no
   hardcode_automatic=yes
   hardcode_shlibpath_var=unsupported
-  if test "$lt_cv_ld_force_load" = "yes"; then
-    whole_archive_flag_spec='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+  if test yes = "$lt_cv_ld_force_load"; then
+    whole_archive_flag_spec='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
 
   else
     whole_archive_flag_spec=''
   fi
   link_all_deplibs=yes
-  allow_undefined_flag="$_lt_dar_allow_undefined"
+  allow_undefined_flag=$_lt_dar_allow_undefined
   case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
+     ifort*|nagfor*) _lt_dar_can_shared=yes ;;
      *) _lt_dar_can_shared=$GCC ;;
   esac
-  if test "$_lt_dar_can_shared" = "yes"; then
+  if test yes = "$_lt_dar_can_shared"; then
     output_verbose_link_cmd=func_echo_all
-    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-    module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
-    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil"
+    module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil"
+    archive_expsym_cmds="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil"
+    module_expsym_cmds="sed -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil"
 
   else
   ld_shlibs=no
@@ -10327,33 +10553,33 @@ fi
       ;;
 
     hpux9*)
-      if test "$GCC" = yes; then
-	archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      if test yes = "$GCC"; then
+	archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
       else
-	archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+	archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
       fi
-      hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+      hardcode_libdir_flag_spec='$wl+b $wl$libdir'
       hardcode_libdir_separator=:
       hardcode_direct=yes
 
       # hardcode_minus_L: Not really in the search PATH,
       # but as the default location of the library.
       hardcode_minus_L=yes
-      export_dynamic_flag_spec='${wl}-E'
+      export_dynamic_flag_spec='$wl-E'
       ;;
 
     hpux10*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes,no = "$GCC,$with_gnu_ld"; then
+	archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
       else
 	archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
       fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+      if test no = "$with_gnu_ld"; then
+	hardcode_libdir_flag_spec='$wl+b $wl$libdir'
 	hardcode_libdir_separator=:
 	hardcode_direct=yes
 	hardcode_direct_absolute=yes
-	export_dynamic_flag_spec='${wl}-E'
+	export_dynamic_flag_spec='$wl-E'
 	# hardcode_minus_L: Not really in the search PATH,
 	# but as the default location of the library.
 	hardcode_minus_L=yes
@@ -10361,25 +10587,25 @@ fi
       ;;
 
     hpux11*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+      if test yes,no = "$GCC,$with_gnu_ld"; then
 	case $host_cpu in
 	hppa*64*)
-	  archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	ia64*)
-	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
 	case $host_cpu in
 	hppa*64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	ia64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
 
@@ -10391,7 +10617,7 @@ if ${lt_cv_prog_compiler__b+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   lt_cv_prog_compiler__b=no
-   save_LDFLAGS="$LDFLAGS"
+   save_LDFLAGS=$LDFLAGS
    LDFLAGS="$LDFLAGS -b"
    echo "$lt_simple_link_test_code" > conftest.$ac_ext
    if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
@@ -10410,14 +10636,14 @@ else
      fi
    fi
    $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
+   LDFLAGS=$save_LDFLAGS
 
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5
 $as_echo "$lt_cv_prog_compiler__b" >&6; }
 
-if test x"$lt_cv_prog_compiler__b" = xyes; then
-    archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+if test yes = "$lt_cv_prog_compiler__b"; then
+    archive_cmds='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 else
     archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
 fi
@@ -10425,8 +10651,8 @@ fi
 	  ;;
 	esac
       fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+      if test no = "$with_gnu_ld"; then
+	hardcode_libdir_flag_spec='$wl+b $wl$libdir'
 	hardcode_libdir_separator=:
 
 	case $host_cpu in
@@ -10437,7 +10663,7 @@ fi
 	*)
 	  hardcode_direct=yes
 	  hardcode_direct_absolute=yes
-	  export_dynamic_flag_spec='${wl}-E'
+	  export_dynamic_flag_spec='$wl-E'
 
 	  # hardcode_minus_L: Not really in the search PATH,
 	  # but as the default location of the library.
@@ -10448,8 +10674,8 @@ fi
       ;;
 
     irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      if test yes = "$GCC"; then
+	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
 	# Try to use the -exported_symbol ld option, if it does not
 	# work, assume that -exports_file does not work either and
 	# implicitly export all symbols.
@@ -10459,8 +10685,8 @@ $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >
 if ${lt_cv_irix_exported_symbol+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  save_LDFLAGS="$LDFLAGS"
-	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+  save_LDFLAGS=$LDFLAGS
+	   LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null"
 	   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 int foo (void) { return 0; }
@@ -10472,24 +10698,35 @@ else
 fi
 rm -f core conftest.err conftest.$ac_objext \
     conftest$ac_exeext conftest.$ac_ext
-           LDFLAGS="$save_LDFLAGS"
+           LDFLAGS=$save_LDFLAGS
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5
 $as_echo "$lt_cv_irix_exported_symbol" >&6; }
-	if test "$lt_cv_irix_exported_symbol" = yes; then
-          archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	if test yes = "$lt_cv_irix_exported_symbol"; then
+          archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib'
 	fi
+	link_all_deplibs=no
       else
-	archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+	archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
+	archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib'
       fi
       archive_cmds_need_lc='no'
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
       hardcode_libdir_separator=:
       inherit_rpath=yes
       link_all_deplibs=yes
       ;;
 
+    linux*)
+      case $cc_basename in
+      tcc*)
+	# Fabrice Bellard et al's Tiny C Compiler
+	ld_shlibs=yes
+	archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	;;
+      esac
+      ;;
+
     netbsd* | netbsdelf*-gnu)
       if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
 	archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
@@ -10504,7 +10741,7 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
     newsos6)
       archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
       hardcode_direct=yes
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
       hardcode_libdir_separator=:
       hardcode_shlibpath_var=no
       ;;
@@ -10512,27 +10749,19 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
     *nto* | *qnx*)
       ;;
 
-    openbsd*)
+    openbsd* | bitrig*)
       if test -f /usr/libexec/ld.so; then
 	hardcode_direct=yes
 	hardcode_shlibpath_var=no
 	hardcode_direct_absolute=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
 	  archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-	  export_dynamic_flag_spec='${wl}-E'
+	  archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols'
+	  hardcode_libdir_flag_spec='$wl-rpath,$libdir'
+	  export_dynamic_flag_spec='$wl-E'
 	else
-	  case $host_os in
-	   openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	     archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     hardcode_libdir_flag_spec='-R$libdir'
-	     ;;
-	   *)
-	     archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-	     ;;
-	  esac
+	  archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  hardcode_libdir_flag_spec='$wl-rpath,$libdir'
 	fi
       else
 	ld_shlibs=no
@@ -10543,33 +10772,53 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
       hardcode_libdir_flag_spec='-L$libdir'
       hardcode_minus_L=yes
       allow_undefined_flag=unsupported
-      archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      shrext_cmds=.dll
+      archive_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      archive_expsym_cmds='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	prefix_cmds="$SED"~
+	if test EXPORTS = "`$SED 1q $export_symbols`"; then
+	  prefix_cmds="$prefix_cmds -e 1d";
+	fi~
+	prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~
+	cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def'
+      enable_shared_with_static_runtimes=yes
       ;;
 
     osf3*)
-      if test "$GCC" = yes; then
-	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      if test yes = "$GCC"; then
+	allow_undefined_flag=' $wl-expect_unresolved $wl\*'
+	archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
       else
 	allow_undefined_flag=' -expect_unresolved \*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
       fi
       archive_cmds_need_lc='no'
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
       hardcode_libdir_separator=:
       ;;
 
     osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      if test yes = "$GCC"; then
+	allow_undefined_flag=' $wl-expect_unresolved $wl\*'
+	archive_cmds='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
+	hardcode_libdir_flag_spec='$wl-rpath $wl$libdir'
       else
 	allow_undefined_flag=' -expect_unresolved \*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	archive_cmds='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
 	archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+          $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
 	hardcode_libdir_flag_spec='-rpath $libdir'
@@ -10580,24 +10829,24 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
 
     solaris*)
       no_undefined_flag=' -z defs'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	wlarc='$wl'
+	archive_cmds='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+          $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
       else
 	case `$CC -V 2>&1` in
 	*"Compilers 5.0"*)
 	  wlarc=''
-	  archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  archive_cmds='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags'
 	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+            $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
 	  ;;
 	*)
-	  wlarc='${wl}'
-	  archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  wlarc='$wl'
+	  archive_cmds='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags'
 	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+            $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
 	  ;;
 	esac
       fi
@@ -10607,11 +10856,11 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
       solaris2.[0-5] | solaris2.[0-5].*) ;;
       *)
 	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but understands '-z linker_flag'.  GCC discards it without '$wl',
 	# but is careful enough not to reorder.
 	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	if test yes = "$GCC"; then
+	  whole_archive_flag_spec='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract'
 	else
 	  whole_archive_flag_spec='-z allextract$convenience -z defaultextract'
 	fi
@@ -10621,10 +10870,10 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
       ;;
 
     sunos4*)
-      if test "x$host_vendor" = xsequent; then
+      if test sequent = "$host_vendor"; then
 	# Use $CC to link under sequent, because it throws in some extra .o
 	# files that make .init and .fini sections work.
-	archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags'
       else
 	archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
       fi
@@ -10673,43 +10922,43 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
       ;;
 
     sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
-      no_undefined_flag='${wl}-z,text'
+      no_undefined_flag='$wl-z,text'
       archive_cmds_need_lc=no
       hardcode_shlibpath_var=no
       runpath_var='LD_RUN_PATH'
 
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
       ;;
 
     sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
+      # Note: We CANNOT use -z defs as we might desire, because we do not
       # link with -lc, and that would cause any symbols used from libc to
       # always be unresolved, which means just about no library would
       # ever link correctly.  If we're not using GNU ld we use -z text
       # though, which does catch some bad symbols but isn't as heavy-handed
       # as -z defs.
-      no_undefined_flag='${wl}-z,text'
-      allow_undefined_flag='${wl}-z,nodefs'
+      no_undefined_flag='$wl-z,text'
+      allow_undefined_flag='$wl-z,nodefs'
       archive_cmds_need_lc=no
       hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='${wl}-R,$libdir'
+      hardcode_libdir_flag_spec='$wl-R,$libdir'
       hardcode_libdir_separator=':'
       link_all_deplibs=yes
-      export_dynamic_flag_spec='${wl}-Bexport'
+      export_dynamic_flag_spec='$wl-Bexport'
       runpath_var='LD_RUN_PATH'
 
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	archive_cmds='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_cmds='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
       ;;
 
@@ -10724,10 +10973,10 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
       ;;
     esac
 
-    if test x$host_vendor = xsni; then
+    if test sni = "$host_vendor"; then
       case $host in
       sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	export_dynamic_flag_spec='${wl}-Blargedynsym'
+	export_dynamic_flag_spec='$wl-Blargedynsym'
 	;;
       esac
     fi
@@ -10735,7 +10984,7 @@ $as_echo "$lt_cv_irix_exported_symbol" >&6; }
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5
 $as_echo "$ld_shlibs" >&6; }
-test "$ld_shlibs" = no && can_build_shared=no
+test no = "$ld_shlibs" && can_build_shared=no
 
 with_gnu_ld=$with_gnu_ld
 
@@ -10761,7 +11010,7 @@ x|xyes)
   # Assume -lc should be added
   archive_cmds_need_lc=yes
 
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
+  if test yes,yes = "$GCC,$enable_shared"; then
     case $archive_cmds in
     *'~'*)
       # FIXME: we may have to deal with multi-command sequences.
@@ -10976,14 +11225,14 @@ esac
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5
 $as_echo_n "checking dynamic linker characteristics... " >&6; }
 
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) lt_awk_arg="/^libraries:/" ;;
+    darwin*) lt_awk_arg='/^libraries:/,/LR/' ;;
+    *) lt_awk_arg='/^libraries:/' ;;
   esac
   case $host_os in
-    mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;;
-    *) lt_sed_strip_eq="s,=/,/,g" ;;
+    mingw* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;;
+    *) lt_sed_strip_eq='s|=/|/|g' ;;
   esac
   lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
   case $lt_search_path_spec in
@@ -10999,28 +11248,35 @@ if test "$GCC" = yes; then
     ;;
   esac
   # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
+  # and add multilib dir if necessary...
   lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  # ...but if some path component already ends with the multilib dir we assume
+  # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer).
+  case "$lt_multi_os_dir; $lt_search_path_spec " in
+  "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*)
+    lt_multi_os_dir=
+    ;;
+  esac
   for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
+    if test -d "$lt_sys_path$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir"
+    elif test -n "$lt_multi_os_dir"; then
       test -d "$lt_sys_path" && \
 	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
     fi
   done
   lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
+BEGIN {RS = " "; FS = "/|\n";} {
+  lt_foo = "";
+  lt_count = 0;
   for (lt_i = NF; lt_i > 0; lt_i--) {
     if ($lt_i != "" && $lt_i != ".") {
       if ($lt_i == "..") {
         lt_count++;
       } else {
         if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
+          lt_foo = "/" $lt_i lt_foo;
         } else {
           lt_count--;
         }
@@ -11034,7 +11290,7 @@ BEGIN {RS=" "; FS="/|\n";} {
   # for these hosts.
   case $host_os in
     mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
-      $SED 's,/\([A-Za-z]:\),\1,g'` ;;
+      $SED 's|/\([A-Za-z]:\)|\1|g'` ;;
   esac
   sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
 else
@@ -11043,7 +11299,7 @@ fi
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
-shrext_cmds=".so"
+shrext_cmds=.so
 postinstall_cmds=
 postuninstall_cmds=
 finish_cmds=
@@ -11060,14 +11316,16 @@ hardcode_into_libs=no
 # flags to be left without arguments
 need_version=unknown
 
+
+
 case $host_os in
 aix3*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname.a'
   shlibpath_var=LIBPATH
 
   # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
+  soname_spec='$libname$release$shared_ext$major'
   ;;
 
 aix[4-9]*)
@@ -11075,41 +11333,91 @@ aix[4-9]*)
   need_lib_prefix=no
   need_version=no
   hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
+  if test ia64 = "$host_cpu"; then
     # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext'
     shlibpath_var=LD_LIBRARY_PATH
   else
     # With GCC up to 2.95.x, collect2 would create an import file
     # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
+    # the line '#! .'.  This would cause the generated library to
+    # depend on '.', always an invalid library.  This was fixed in
     # development snapshots of GCC prior to 3.0.
     case $host_os in
       aix4 | aix4.[01] | aix4.[01].*)
       if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
 	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	   echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then
 	:
       else
 	can_build_shared=no
       fi
       ;;
     esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # Using Import Files as archive members, it is possible to support
+    # filename-based versioning of shared library archives on AIX. While
+    # this would work for both with and without runtime linking, it will
+    # prevent static linking of such archives. So we do filename-based
+    # shared library versioning with .so extension only, which is used
+    # when both runtime linking and shared linking is enabled.
+    # Unfortunately, runtime linking may impact performance, so we do
+    # not want this to be the default eventually. Also, we use the
+    # versioned .so libs for executables only if there is the -brtl
+    # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only.
+    # To allow for filename-based versioning support, we need to create
+    # libNAME.so.V as an archive file, containing:
+    # *) an Import File, referring to the versioned filename of the
+    #    archive as well as the shared archive member, telling the
+    #    bitwidth (32 or 64) of that shared object, and providing the
+    #    list of exported symbols of that shared object, eventually
+    #    decorated with the 'weak' keyword
+    # *) the shared object with the F_LOADONLY flag set, to really avoid
+    #    it being seen by the linker.
+    # At run time we better use the real file rather than another symlink,
+    # but for link time we create the symlink libNAME.so -> libNAME.so.V
+
+    case $with_aix_soname,$aix_use_runtimelinking in
+    # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct
     # soname into executable. Probably we can add versioning support to
     # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
+    aix,yes) # traditional libtool
+      dynamic_linker='AIX unversionable lib.so'
       # If using run time linking (on AIX 4.2 or later) use lib<name>.so
       # instead of lib<name>.a to let people know that these are not
       # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+      ;;
+    aix,no) # traditional AIX only
+      dynamic_linker='AIX lib.a(lib.so.V)'
       # We preserve .a as extension for shared libraries through AIX4.2
       # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
+      library_names_spec='$libname$release.a $libname.a'
+      soname_spec='$libname$release$shared_ext$major'
+      ;;
+    svr4,*) # full svr4 only
+      dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o)"
+      library_names_spec='$libname$release$shared_ext$major $libname$shared_ext'
+      # We do not specify a path in Import Files, so LIBPATH fires.
+      shlibpath_overrides_runpath=yes
+      ;;
+    *,yes) # both, prefer svr4
+      dynamic_linker="AIX lib.so.V($shared_archive_member_spec.o), lib.a(lib.so.V)"
+      library_names_spec='$libname$release$shared_ext$major $libname$shared_ext'
+      # unpreferred sharedlib libNAME.a needs extra handling
+      postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"'
+      postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"'
+      # We do not specify a path in Import Files, so LIBPATH fires.
+      shlibpath_overrides_runpath=yes
+      ;;
+    *,no) # both, prefer aix
+      dynamic_linker="AIX lib.a(lib.so.V), lib.so.V($shared_archive_member_spec.o)"
+      library_names_spec='$libname$release.a $libname.a'
+      soname_spec='$libname$release$shared_ext$major'
+      # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling
+      postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)'
+      postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"'
+      ;;
+    esac
     shlibpath_var=LIBPATH
   fi
   ;;
@@ -11119,18 +11427,18 @@ amigaos*)
   powerpc)
     # Since July 2007 AmigaOS4 officially supports .so libraries.
     # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
     ;;
   m68k)
     library_names_spec='$libname.ixlibrary $libname.a'
     # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
     ;;
   esac
   ;;
 
 beos*)
-  library_names_spec='${libname}${shared_ext}'
+  library_names_spec='$libname$shared_ext'
   dynamic_linker="$host_os ld.so"
   shlibpath_var=LIBRARY_PATH
   ;;
@@ -11138,8 +11446,8 @@ beos*)
 bsdi[45]*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
@@ -11151,7 +11459,7 @@ bsdi[45]*)
 
 cygwin* | mingw* | pw32* | cegcc*)
   version_type=windows
-  shrext_cmds=".dll"
+  shrext_cmds=.dll
   need_version=no
   need_lib_prefix=no
 
@@ -11160,8 +11468,8 @@ cygwin* | mingw* | pw32* | cegcc*)
     # gcc
     library_names_spec='$libname.dll.a'
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+    postinstall_cmds='base_file=`basename \$file`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
       $install_prog $dir/$dlname \$dldir/$dlname~
@@ -11177,17 +11485,17 @@ cygwin* | mingw* | pw32* | cegcc*)
     case $host_os in
     cygwin*)
       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      soname_spec='`echo $libname | sed -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
 
       sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
       ;;
     mingw* | cegcc*)
       # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
       ;;
     pw32*)
       # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
+      library_names_spec='`echo $libname | sed -e 's/^lib/pw/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
       ;;
     esac
     dynamic_linker='Win32 ld.exe'
@@ -11196,8 +11504,8 @@ cygwin* | mingw* | pw32* | cegcc*)
   *,cl*)
     # Native MSVC
     libname_spec='$name'
-    soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-    library_names_spec='${libname}.dll.lib'
+    soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+    library_names_spec='$libname.dll.lib'
 
     case $build_os in
     mingw*)
@@ -11224,7 +11532,7 @@ cygwin* | mingw* | pw32* | cegcc*)
       sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
       ;;
     *)
-      sys_lib_search_path_spec="$LIB"
+      sys_lib_search_path_spec=$LIB
       if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then
         # It is most probably a Windows format PATH.
         sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
@@ -11237,8 +11545,8 @@ cygwin* | mingw* | pw32* | cegcc*)
     esac
 
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+    postinstall_cmds='base_file=`basename \$file`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
       $install_prog $dir/$dlname \$dldir/$dlname'
@@ -11251,7 +11559,7 @@ cygwin* | mingw* | pw32* | cegcc*)
 
   *)
     # Assume MSVC wrapper
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    library_names_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext $libname.lib'
     dynamic_linker='Win32 ld.exe'
     ;;
   esac
@@ -11264,8 +11572,8 @@ darwin* | rhapsody*)
   version_type=darwin
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
+  library_names_spec='$libname$release$major$shared_ext $libname$shared_ext'
+  soname_spec='$libname$release$major$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
   shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
@@ -11278,8 +11586,8 @@ dgux*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
@@ -11297,12 +11605,13 @@ freebsd* | dragonfly*)
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+      soname_spec='$libname$release$shared_ext$major'
       need_version=no
       need_lib_prefix=no
       ;;
     freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
       need_version=yes
       ;;
   esac
@@ -11332,10 +11641,10 @@ haiku*)
   need_lib_prefix=no
   need_version=no
   dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
+  shlibpath_overrides_runpath=no
   sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
   hardcode_into_libs=yes
   ;;
@@ -11353,14 +11662,15 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.so"
     shlibpath_var=LD_LIBRARY_PATH
     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
+    if test 32 = "$HPUX_IA64_MODE"; then
       sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+      sys_lib_dlsearch_path_spec=/usr/lib/hpux32
     else
       sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+      sys_lib_dlsearch_path_spec=/usr/lib/hpux64
     fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
     ;;
   hppa*64*)
     shrext_cmds='.sl'
@@ -11368,8 +11678,8 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.sl"
     shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
     sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
     ;;
@@ -11378,8 +11688,8 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.sl"
     shlibpath_var=SHLIB_PATH
     shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     ;;
   esac
   # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
@@ -11392,8 +11702,8 @@ interix[3-9]*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
@@ -11404,7 +11714,7 @@ irix5* | irix6* | nonstopux*)
   case $host_os in
     nonstopux*) version_type=nonstopux ;;
     *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
+	if test yes = "$lt_cv_prog_gnu_ld"; then
 		version_type=linux # correct to gnu/linux during the next big refactor
 	else
 		version_type=irix
@@ -11412,8 +11722,8 @@ irix5* | irix6* | nonstopux*)
   esac
   need_lib_prefix=no
   need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='$libname$release$shared_ext$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext'
   case $host_os in
   irix5* | nonstopux*)
     libsuff= shlibsuff=
@@ -11432,8 +11742,8 @@ irix5* | irix6* | nonstopux*)
   esac
   shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
   shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff"
+  sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff"
   hardcode_into_libs=yes
   ;;
 
@@ -11442,13 +11752,33 @@ linux*oldld* | linux*aout* | linux*coff*)
   dynamic_linker=no
   ;;
 
+linux*android*)
+  version_type=none # Android doesn't support versioned libraries.
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='$libname$release$shared_ext'
+  soname_spec='$libname$release$shared_ext'
+  finish_cmds=
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  dynamic_linker='Android linker'
+  # Don't embed -rpath directories since the linker doesn't support them.
+  hardcode_libdir_flag_spec='-L$libdir'
+  ;;
+
 # This must be glibc/ELF.
 linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
@@ -11492,7 +11822,12 @@ fi
   # before this can be enabled.
   hardcode_into_libs=yes
 
-  # Append ld.so.conf contents to the search path
+  # Ideally, we could use ldconfig to report *all* directores which are
+  # searched for libraries, however this is still not possible.  Aside from not
+  # being certain /sbin/ldconfig is available, command
+  # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64,
+  # even though it is searched at run-time.  Try to do the best guess by
+  # appending ld.so.conf contents (and includes) to the search path.
   if test -f /etc/ld.so.conf; then
     lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
@@ -11524,12 +11859,12 @@ netbsd*)
   need_lib_prefix=no
   need_version=no
   if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
     finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
     dynamic_linker='NetBSD (a.out) ld.so'
   else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     dynamic_linker='NetBSD ld.elf_so'
   fi
   shlibpath_var=LD_LIBRARY_PATH
@@ -11539,7 +11874,7 @@ netbsd*)
 
 newsos6)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   ;;
@@ -11548,58 +11883,68 @@ newsos6)
   version_type=qnx
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
   hardcode_into_libs=yes
   dynamic_linker='ldqnx.so'
   ;;
 
-openbsd*)
+openbsd* | bitrig*)
   version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
+  sys_lib_dlsearch_path_spec=/usr/lib
   need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
+    need_version=no
   else
-    shlibpath_overrides_runpath=yes
+    need_version=yes
   fi
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
   ;;
 
 os2*)
   libname_spec='$name'
-  shrext_cmds=".dll"
+  version_type=windows
+  shrext_cmds=.dll
+  need_version=no
   need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
+  # OS/2 can only load a DLL with a base name of 8 characters or less.
+  soname_spec='`test -n "$os2dllname" && libname="$os2dllname";
+    v=$($ECHO $release$versuffix | tr -d .-);
+    n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _);
+    $ECHO $n$v`$shared_ext'
+  library_names_spec='${libname}_dll.$libext'
   dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
+  shlibpath_var=BEGINLIBPATH
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+  postinstall_cmds='base_file=`basename \$file`~
+    dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~
+    dldir=$destdir/`dirname \$dlpath`~
+    test -d \$dldir || mkdir -p \$dldir~
+    $install_prog $dir/$dlname \$dldir/$dlname~
+    chmod a+x \$dldir/$dlname~
+    if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+      eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+    fi'
+  postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~
+    dlpath=$dir/\$dldll~
+    $RM \$dlpath'
   ;;
 
 osf3* | osf4* | osf5*)
   version_type=osf
   need_lib_prefix=no
   need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='$libname$release$shared_ext$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
   ;;
 
 rdos*)
@@ -11610,8 +11955,8 @@ solaris*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   hardcode_into_libs=yes
@@ -11621,11 +11966,11 @@ solaris*)
 
 sunos4*)
   version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
   finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     need_lib_prefix=no
   fi
   need_version=yes
@@ -11633,8 +11978,8 @@ sunos4*)
 
 sysv4 | sysv4.3*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   case $host_vendor in
     sni)
@@ -11655,24 +12000,24 @@ sysv4 | sysv4.3*)
   ;;
 
 sysv4*MP*)
-  if test -d /usr/nec ;then
+  if test -d /usr/nec; then
     version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
+    library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext'
+    soname_spec='$libname$shared_ext.$major'
     shlibpath_var=LD_LIBRARY_PATH
   fi
   ;;
 
 sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
+  version_type=sco
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
   else
     sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
@@ -11690,7 +12035,7 @@ tpf*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
   hardcode_into_libs=yes
@@ -11698,8 +12043,8 @@ tpf*)
 
 uts4*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
@@ -11709,20 +12054,35 @@ uts4*)
 esac
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
 $as_echo "$dynamic_linker" >&6; }
-test "$dynamic_linker" = no && can_build_shared=no
+test no = "$dynamic_linker" && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then
+  sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec
 fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+
+if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then
+  sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec
 fi
 
+# remember unaugmented sys_lib_dlsearch_path content for libtool script decls...
+configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec
+
+# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code
+func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH"
+
+# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool
+configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH
+
+
+
+
+
+
 
 
 
@@ -11819,15 +12179,15 @@ $as_echo_n "checking how to hardcode library paths into programs... " >&6; }
 hardcode_action=
 if test -n "$hardcode_libdir_flag_spec" ||
    test -n "$runpath_var" ||
-   test "X$hardcode_automatic" = "Xyes" ; then
+   test yes = "$hardcode_automatic"; then
 
   # We can hardcode non-existent directories.
-  if test "$hardcode_direct" != no &&
+  if test no != "$hardcode_direct" &&
      # If the only mechanism to avoid hardcoding is shlibpath_var, we
      # have to relink, otherwise we might link with an installed library
      # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no &&
-     test "$hardcode_minus_L" != no; then
+     ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, )" &&
+     test no != "$hardcode_minus_L"; then
     # Linking always hardcodes the temporary library directory.
     hardcode_action=relink
   else
@@ -11842,12 +12202,12 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
 $as_echo "$hardcode_action" >&6; }
 
-if test "$hardcode_action" = relink ||
-   test "$inherit_rpath" = yes; then
+if test relink = "$hardcode_action" ||
+   test yes = "$inherit_rpath"; then
   # Fast installation is not supported
   enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
+elif test yes = "$shlibpath_overrides_runpath" ||
+     test no = "$enable_shared"; then
   # Fast installation is not necessary
   enable_fast_install=needless
 fi
@@ -11857,7 +12217,7 @@ fi
 
 
 
-  if test "x$enable_dlopen" != xyes; then
+  if test yes != "$enable_dlopen"; then
   enable_dlopen=unknown
   enable_dlopen_self=unknown
   enable_dlopen_self_static=unknown
@@ -11867,23 +12227,23 @@ else
 
   case $host_os in
   beos*)
-    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen=load_add_on
     lt_cv_dlopen_libs=
     lt_cv_dlopen_self=yes
     ;;
 
   mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen=LoadLibrary
     lt_cv_dlopen_libs=
     ;;
 
   cygwin*)
-    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen=dlopen
     lt_cv_dlopen_libs=
     ;;
 
   darwin*)
-  # if libdl is installed we need to link against it
+    # if libdl is installed we need to link against it
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
 $as_echo_n "checking for dlopen in -ldl... " >&6; }
 if ${ac_cv_lib_dl_dlopen+:} false; then :
@@ -11921,10 +12281,10 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
 $as_echo "$ac_cv_lib_dl_dlopen" >&6; }
 if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+  lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl
 else
 
-    lt_cv_dlopen="dyld"
+    lt_cv_dlopen=dyld
     lt_cv_dlopen_libs=
     lt_cv_dlopen_self=yes
 
@@ -11932,10 +12292,18 @@ fi
 
     ;;
 
+  tpf*)
+    # Don't try to run any link tests for TPF.  We know it's impossible
+    # because TPF is a cross-compiler, and we know how we open DSOs.
+    lt_cv_dlopen=dlopen
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=no
+    ;;
+
   *)
     ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
 if test "x$ac_cv_func_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load"
+  lt_cv_dlopen=shl_load
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
 $as_echo_n "checking for shl_load in -ldld... " >&6; }
@@ -11974,11 +12342,11 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
 $as_echo "$ac_cv_lib_dld_shl_load" >&6; }
 if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
+  lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld
 else
   ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
 if test "x$ac_cv_func_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen"
+  lt_cv_dlopen=dlopen
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
 $as_echo_n "checking for dlopen in -ldl... " >&6; }
@@ -12017,7 +12385,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
 $as_echo "$ac_cv_lib_dl_dlopen" >&6; }
 if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
+  lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
 $as_echo_n "checking for dlopen in -lsvld... " >&6; }
@@ -12056,7 +12424,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
 $as_echo "$ac_cv_lib_svld_dlopen" >&6; }
 if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
+  lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
 $as_echo_n "checking for dld_link in -ldld... " >&6; }
@@ -12095,7 +12463,7 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
 $as_echo "$ac_cv_lib_dld_dld_link" >&6; }
 if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
-  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
+  lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld
 fi
 
 
@@ -12116,21 +12484,21 @@ fi
     ;;
   esac
 
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
+  if test no = "$lt_cv_dlopen"; then
     enable_dlopen=no
+  else
+    enable_dlopen=yes
   fi
 
   case $lt_cv_dlopen in
   dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+    save_CPPFLAGS=$CPPFLAGS
+    test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
-    save_LDFLAGS="$LDFLAGS"
+    save_LDFLAGS=$LDFLAGS
     wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
-    save_LIBS="$LIBS"
+    save_LIBS=$LIBS
     LIBS="$lt_cv_dlopen_libs $LIBS"
 
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
@@ -12138,7 +12506,7 @@ $as_echo_n "checking whether a program can dlopen itself... " >&6; }
 if ${lt_cv_dlopen_self+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  	  if test "$cross_compiling" = yes; then :
+  	  if test yes = "$cross_compiling"; then :
   lt_cv_dlopen_self=cross
 else
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
@@ -12185,9 +12553,9 @@ else
 #  endif
 #endif
 
-/* When -fvisbility=hidden is used, assume the code has been annotated
+/* When -fvisibility=hidden is used, assume the code has been annotated
    correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
 int fnord () __attribute__((visibility("default")));
 #endif
 
@@ -12217,7 +12585,7 @@ _LT_EOF
   (eval $ac_link) 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+  test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then
     (./conftest; exit; ) >&5 2>/dev/null
     lt_status=$?
     case x$lt_status in
@@ -12237,14 +12605,14 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
 $as_echo "$lt_cv_dlopen_self" >&6; }
 
-    if test "x$lt_cv_dlopen_self" = xyes; then
+    if test yes = "$lt_cv_dlopen_self"; then
       wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
 if ${lt_cv_dlopen_self_static+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  	  if test "$cross_compiling" = yes; then :
+  	  if test yes = "$cross_compiling"; then :
   lt_cv_dlopen_self_static=cross
 else
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
@@ -12291,9 +12659,9 @@ else
 #  endif
 #endif
 
-/* When -fvisbility=hidden is used, assume the code has been annotated
+/* When -fvisibility=hidden is used, assume the code has been annotated
    correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
 int fnord () __attribute__((visibility("default")));
 #endif
 
@@ -12323,7 +12691,7 @@ _LT_EOF
   (eval $ac_link) 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
+  test $ac_status = 0; } && test -s "conftest$ac_exeext" 2>/dev/null; then
     (./conftest; exit; ) >&5 2>/dev/null
     lt_status=$?
     case x$lt_status in
@@ -12344,9 +12712,9 @@ fi
 $as_echo "$lt_cv_dlopen_self_static" >&6; }
     fi
 
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
+    CPPFLAGS=$save_CPPFLAGS
+    LDFLAGS=$save_LDFLAGS
+    LIBS=$save_LIBS
     ;;
   esac
 
@@ -12390,7 +12758,7 @@ else
 # FIXME - insert some real tests, host_os isn't really good enough
   case $host_os in
   darwin*)
-    if test -n "$STRIP" ; then
+    if test -n "$STRIP"; then
       striplib="$STRIP -x"
       old_striplib="$STRIP -S"
       { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
@@ -12418,7 +12786,7 @@ fi
 
 
 
-  # Report which library types will actually be built
+  # Report what library types will actually be built
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5
 $as_echo_n "checking if libtool supports shared libraries... " >&6; }
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
@@ -12426,13 +12794,13 @@ $as_echo "$can_build_shared" >&6; }
 
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5
 $as_echo_n "checking whether to build shared libraries... " >&6; }
-  test "$can_build_shared" = "no" && enable_shared=no
+  test no = "$can_build_shared" && enable_shared=no
 
   # On AIX, shared libraries and static libraries use the same namespace, and
   # are all built from PIC.
   case $host_os in
   aix3*)
-    test "$enable_shared" = yes && enable_static=no
+    test yes = "$enable_shared" && enable_static=no
     if test -n "$RANLIB"; then
       archive_cmds="$archive_cmds~\$RANLIB \$lib"
       postinstall_cmds='$RANLIB $lib'
@@ -12440,8 +12808,12 @@ $as_echo_n "checking whether to build shared libraries... " >&6; }
     ;;
 
   aix[4-9]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
+    if test ia64 != "$host_cpu"; then
+      case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in
+      yes,aix,yes) ;;			# shared object as lib.so file only
+      yes,svr4,*) ;;			# shared object as lib.so archive member only
+      yes,*) enable_static=no ;;	# shared object in lib.a archive as well
+      esac
     fi
     ;;
   esac
@@ -12451,7 +12823,7 @@ $as_echo "$enable_shared" >&6; }
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5
 $as_echo_n "checking whether to build static libraries... " >&6; }
   # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
+  test yes = "$enable_shared" || enable_static=yes
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
 $as_echo "$enable_static" >&6; }
 
@@ -12465,7 +12837,7 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-CC="$lt_save_CC"
+CC=$lt_save_CC
 
 
 
@@ -12490,6 +12862,75 @@ CC="$lt_save_CC"
 
 
 
+# Set up the libsigrokdecode version defines.
+SRD_PACKAGE_VERSION=0.4.1
+sr_git_deps=
+# Check if we can get revision information from git.
+sr_head=`git -C "$srcdir" rev-parse --verify --short HEAD 2>&5`
+
+if test "$?" = 0 && test "x$sr_head" != x; then :
+  	test ! -f "$srcdir/.git/HEAD" \
+		|| sr_git_deps="$sr_git_deps \$(top_srcdir)/.git/HEAD"
+
+	sr_head_name=`git -C "$srcdir" rev-parse --symbolic-full-name HEAD 2>&5`
+	if test "$?" = 0 && test -f "$srcdir/.git/$sr_head_name"; then :
+  sr_git_deps="$sr_git_deps \$(top_srcdir)/.git/$sr_head_name"
+fi
+
+	# Append the revision hash unless we are exactly on a tagged release.
+	git -C "$srcdir" describe --match "libsigrokdecode-0.4.1" \
+		--exact-match >&5 2>&5 \
+		|| SRD_PACKAGE_VERSION="$SRD_PACKAGE_VERSION-git-$sr_head"
+
+fi
+# Use $(wildcard) so that things do not break if for whatever
+# reason these files do not exist anymore at make time.
+if test -n "$sr_git_deps"; then :
+  CONFIG_STATUS_DEPENDENCIES=${CONFIG_STATUS_DEPENDENCIES}${CONFIG_STATUS_DEPENDENCIES:+' '}"\$(wildcard$sr_git_deps)"
+fi
+
+$as_echo "#define SRD_PACKAGE_VERSION_MAJOR 0" >>confdefs.h
+
+$as_echo "#define SRD_PACKAGE_VERSION_MINOR 4" >>confdefs.h
+
+$as_echo "#define SRD_PACKAGE_VERSION_MICRO 1" >>confdefs.h
+
+cat >>confdefs.h <<_ACEOF
+#define SRD_PACKAGE_VERSION_STRING "$SRD_PACKAGE_VERSION"
+_ACEOF
+
+
+
+# Library version for libsigrokdecode (NOT the same as the package version).
+# Carefully read the libtool docs before updating these numbers!
+# The algorithm for determining which number to change (and how) is nontrivial!
+# http://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info
+# Format: current:revision:age.
+SRD_LIB_VERSION=3:1:0
+
+$as_echo "#define SRD_LIB_VERSION_CURRENT 3" >>confdefs.h
+
+$as_echo "#define SRD_LIB_VERSION_REVISION 1" >>confdefs.h
+
+$as_echo "#define SRD_LIB_VERSION_AGE 0" >>confdefs.h
+
+$as_echo "#define SRD_LIB_VERSION_STRING \"3:1:0\"" >>confdefs.h
+
+
+
+ if test -z "${host_os##mingw*}" || test -z "${host_os##cygwin*}"; then
+  WIN32_TRUE=
+  WIN32_FALSE='#'
+else
+  WIN32_TRUE='#'
+  WIN32_FALSE=
+fi
+
+
+############################
+##  Package dependencies  ##
+############################
+
 # Initialize pkg-config.
 # We require at least 0.22, as "Requires.private" behaviour changed there.
 
@@ -12613,88 +13054,134 @@ $as_echo "no" >&6; }
 	fi
 fi
 
-# Library version for libsigrokdecode (NOT the same as the package version).
-# Carefully read the libtool docs before updating these numbers!
-# The algorithm for determining which number to change (and how) is nontrivial!
-# http://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info
-SRD_LIB_VERSION_CURRENT=2
-SRD_LIB_VERSION_REVISION=0
-SRD_LIB_VERSION_AGE=0
-SRD_LIB_VERSION="$SRD_LIB_VERSION_CURRENT:$SRD_LIB_VERSION_REVISION:$SRD_LIB_VERSION_AGE"
-SRD_LIB_LDFLAGS="-version-info $SRD_LIB_VERSION"
-
-
+# Collect the pkg-config module names of all dependencies in SRD_PKGLIBS.
+# These are used to derive the compiler flags and for the "Requires.private"
+# field in the generated libsigrokdecode.pc file.
+SRD_PKGLIBS=
+SRD_PKGLIBS_TESTS=
 
+# Keep track of all checked modules so we can list them at the end.
+srd_pkglibs_summary=
+sr_pkg_check_summary_append() {
+	sr_aligned=`printf '%.32s' "$1................................"`
+	srd_pkglibs_summary="${srd_pkglibs_summary} - $sr_aligned $2"'
+'
+}
 
 
-
-# Assume we can build tests/runtc unless proven otherwise.
-build_runtc="yes"
-
-# Checks for libraries.
-
-# libglib-2.0 is always needed.
-# Note: glib-2.0 is part of the libsigrokdecode API
-# (hard pkg-config requirement).
-# Check whether --enable-glibtest was given.
-if test "${enable_glibtest+set}" = set; then :
-  enableval=$enable_glibtest;
+# Python 3 is always needed.
+if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python3 >= 3.2\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python3 >= 3.2") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python3 >= 3.2"
+	sr_python3_version=`$PKG_CONFIG --modversion "python3 >= 3.2" 2>&5`
+	sr_pkg_check_summary_append "python3 >= 3.2" "$sr_python3_version"
+else
+  	sr_pkg_check_summary_append "python3 >= 3.2" no
+	if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.6 >= 3.6\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python-3.6 >= 3.6") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python-3.6 >= 3.6"
+	sr_python3_version=`$PKG_CONFIG --modversion "python-3.6 >= 3.6" 2>&5`
+	sr_pkg_check_summary_append "python-3.6 >= 3.6" "$sr_python3_version"
+else
+  	sr_pkg_check_summary_append "python-3.6 >= 3.6" no
+	if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.5 >= 3.5\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python-3.5 >= 3.5") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python-3.5 >= 3.5"
+	sr_python3_version=`$PKG_CONFIG --modversion "python-3.5 >= 3.5" 2>&5`
+	sr_pkg_check_summary_append "python-3.5 >= 3.5" "$sr_python3_version"
+else
+  	sr_pkg_check_summary_append "python-3.5 >= 3.5" no
+	if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.4 >= 3.4\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python-3.4 >= 3.4") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python-3.4 >= 3.4"
+	sr_python3_version=`$PKG_CONFIG --modversion "python-3.4 >= 3.4" 2>&5`
+	sr_pkg_check_summary_append "python-3.4 >= 3.4" "$sr_python3_version"
+else
+  	sr_pkg_check_summary_append "python-3.4 >= 3.4" no
+	if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python-3.3 >= 3.3"
+	sr_python3_version=`$PKG_CONFIG --modversion "python-3.3 >= 3.3" 2>&5`
+	sr_pkg_check_summary_append "python-3.3 >= 3.3" "$sr_python3_version"
+else
+  	sr_pkg_check_summary_append "python-3.3 >= 3.3" no
+	if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_python3=yes
+	SRD_PKGLIBS=${SRD_PKGLIBS}${SRD_PKGLIBS:+' '}"python-3.2 >= 3.2"
+	sr_python3_version=`$PKG_CONFIG --modversion "python-3.2 >= 3.2" 2>&5`
+	sr_pkg_check_summary_append "python-3.2 >= 3.2" "$sr_python3_version"
 else
-  enable_glibtest=yes
+  	sr_pkg_check_summary_append "python-3.2 >= 3.2" no
+	sr_have_python3=no sr_python3_version=
 fi
 
+fi
 
-  pkg_config_args=glib-2.0
-  for module in .
-  do
-      case "$module" in
-         gmodule)
-             pkg_config_args="$pkg_config_args gmodule-2.0"
-         ;;
-         gmodule-no-export)
-             pkg_config_args="$pkg_config_args gmodule-no-export-2.0"
-         ;;
-         gobject)
-             pkg_config_args="$pkg_config_args gobject-2.0"
-         ;;
-         gthread)
-             pkg_config_args="$pkg_config_args gthread-2.0"
-         ;;
-         gio*)
-             pkg_config_args="$pkg_config_args $module-2.0"
-         ;;
-      esac
-  done
-
-
+fi
 
+fi
 
+fi
 
+fi
 
+if test "x$sr_have_python3" = xno; then :
+  as_fn_error $? "Cannot find Python 3 development headers." "$LINENO" 5
+fi
 
+# We also need to find the name of the python3 executable (for 'make install').
+# Some OSes call this python3, some call it python3.2, etc. etc.
 
-if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
-	if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args.
-set dummy ${ac_tool_prefix}pkg-config; ac_word=$2
+for ac_prog in python3.6 python3.5 python3.4 python3.3 python3.2 python3
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_PKG_CONFIG+:} false; then :
+if ${ac_cv_prog_PYTHON3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  case $PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+  if test -n "$PYTHON3"; then
+  ac_cv_prog_PYTHON3="$PYTHON3" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    ac_cv_prog_PYTHON3="$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -12702,1594 +13189,189 @@ done
   done
 IFS=$as_save_IFS
 
-  ;;
-esac
 fi
-PKG_CONFIG=$ac_cv_path_PKG_CONFIG
-if test -n "$PKG_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
-$as_echo "$PKG_CONFIG" >&6; }
+fi
+PYTHON3=$ac_cv_prog_PYTHON3
+if test -n "$PYTHON3"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON3" >&5
+$as_echo "$PYTHON3" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
 
-fi
-if test -z "$ac_cv_path_PKG_CONFIG"; then
-  ac_pt_PKG_CONFIG=$PKG_CONFIG
-  # Extract the first word of "pkg-config", so it can be a program name with args.
-set dummy pkg-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $ac_pt_PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
+  test -n "$PYTHON3" && break
 done
-  done
-IFS=$as_save_IFS
 
-  ;;
-esac
-fi
-ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG
-if test -n "$ac_pt_PKG_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5
-$as_echo "$ac_pt_PKG_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+if test "x$PYTHON3" = x; then :
+  as_fn_error $? "Cannot find Python 3 interpreter." "$LINENO" 5
 fi
 
-  if test "x$ac_pt_PKG_CONFIG" = x; then
-    PKG_CONFIG=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    PKG_CONFIG=$ac_pt_PKG_CONFIG
-  fi
-else
-  PKG_CONFIG="$ac_cv_path_PKG_CONFIG"
-fi
-
-fi
-if test -n "$PKG_CONFIG"; then
-	_pkg_min_version=0.16
-	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5
-$as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; }
-	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	else
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-		PKG_CONFIG=""
-	fi
-fi
-
-  no_glib=""
-
-  if test "x$PKG_CONFIG" = x ; then
-    no_glib=yes
-    PKG_CONFIG=no
-  fi
-
-  min_glib_version=2.24.0
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GLIB - version >= $min_glib_version" >&5
-$as_echo_n "checking for GLIB - version >= $min_glib_version... " >&6; }
-
-  if test x$PKG_CONFIG != xno ; then
-    ## don't try to run the test against uninstalled libtool libs
-    if $PKG_CONFIG --uninstalled $pkg_config_args; then
-	  echo "Will use uninstalled version of GLib found in PKG_CONFIG_PATH"
-	  enable_glibtest=no
-    fi
-
-    if $PKG_CONFIG --atleast-version $min_glib_version $pkg_config_args; then
-	  :
-    else
-	  no_glib=yes
-    fi
-  fi
-
-  if test x"$no_glib" = x ; then
-    GLIB_GENMARSHAL=`$PKG_CONFIG --variable=glib_genmarshal glib-2.0`
-    GOBJECT_QUERY=`$PKG_CONFIG --variable=gobject_query glib-2.0`
-    GLIB_MKENUMS=`$PKG_CONFIG --variable=glib_mkenums glib-2.0`
-    GLIB_COMPILE_RESOURCES=`$PKG_CONFIG --variable=glib_compile_resources gio-2.0`
-
-    GLIB_CFLAGS=`$PKG_CONFIG --cflags $pkg_config_args`
-    GLIB_LIBS=`$PKG_CONFIG --libs $pkg_config_args`
-    glib_config_major_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1/'`
-    glib_config_minor_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\2/'`
-    glib_config_micro_version=`$PKG_CONFIG --modversion glib-2.0 | \
-           sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\3/'`
-    if test "x$enable_glibtest" = "xyes" ; then
-      ac_save_CFLAGS="$CFLAGS"
-      ac_save_LIBS="$LIBS"
-      CFLAGS="$CFLAGS $GLIB_CFLAGS"
-      LIBS="$GLIB_LIBS $LIBS"
-      rm -f conf.glibtest
-      if test "$cross_compiling" = yes; then :
-  echo $ac_n "cross compiling; assumed OK... $ac_c"
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-#include <glib.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-int
-main ()
-{
-  unsigned int major, minor, micro;
-
-  fclose (fopen ("conf.glibtest", "w"));
+######################
+##  Feature checks  ##
+######################
 
-  if (sscanf("$min_glib_version", "%u.%u.%u", &major, &minor, &micro) != 3) {
-     printf("%s, bad version string\n", "$min_glib_version");
-     exit(1);
-   }
-
-  if ((glib_major_version != $glib_config_major_version) ||
-      (glib_minor_version != $glib_config_minor_version) ||
-      (glib_micro_version != $glib_config_micro_version))
-    {
-      printf("\n*** 'pkg-config --modversion glib-2.0' returned %d.%d.%d, but GLIB (%d.%d.%d)\n",
-             $glib_config_major_version, $glib_config_minor_version, $glib_config_micro_version,
-             glib_major_version, glib_minor_version, glib_micro_version);
-      printf ("*** was found! If pkg-config was correct, then it is best\n");
-      printf ("*** to remove the old version of GLib. You may also be able to fix the error\n");
-      printf("*** by modifying your LD_LIBRARY_PATH enviroment variable, or by editing\n");
-      printf("*** /etc/ld.so.conf. Make sure you have run ldconfig if that is\n");
-      printf("*** required on your system.\n");
-      printf("*** If pkg-config was wrong, set the environment variable PKG_CONFIG_PATH\n");
-      printf("*** to point to the correct configuration files\n");
-    }
-  else if ((glib_major_version != GLIB_MAJOR_VERSION) ||
-	   (glib_minor_version != GLIB_MINOR_VERSION) ||
-           (glib_micro_version != GLIB_MICRO_VERSION))
-    {
-      printf("*** GLIB header files (version %d.%d.%d) do not match\n",
-	     GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
-      printf("*** library (version %d.%d.%d)\n",
-	     glib_major_version, glib_minor_version, glib_micro_version);
-    }
-  else
-    {
-      if ((glib_major_version > major) ||
-        ((glib_major_version == major) && (glib_minor_version > minor)) ||
-        ((glib_major_version == major) && (glib_minor_version == minor) && (glib_micro_version >= micro)))
-      {
-        return 0;
-       }
-     else
-      {
-        printf("\n*** An old version of GLIB (%u.%u.%u) was found.\n",
-               glib_major_version, glib_minor_version, glib_micro_version);
-        printf("*** You need a version of GLIB newer than %u.%u.%u. The latest version of\n",
-	       major, minor, micro);
-        printf("*** GLIB is always available from ftp://ftp.gtk.org.\n");
-        printf("***\n");
-        printf("*** If you have already installed a sufficiently new version, this error\n");
-        printf("*** probably means that the wrong copy of the pkg-config shell script is\n");
-        printf("*** being found. The easiest way to fix this is to remove the old version\n");
-        printf("*** of GLIB, but you can also set the PKG_CONFIG environment to point to the\n");
-        printf("*** correct copy of pkg-config. (In this case, you will have to\n");
-        printf("*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf\n");
-        printf("*** so that the correct libraries are found at run-time))\n");
-      }
-    }
-  return 1;
+# Keep track of all checked modules so we can list them at the end.
+srd_pkglibs_opt_summary=
+sr_pkg_check_summary_append() {
+	sr_aligned=`printf '%.32s' "$1................................"`
+	srd_pkglibs_opt_summary="${srd_pkglibs_opt_summary} - $sr_aligned $2"'
+'
 }
 
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
 
+# The Check unit testing framework is optional. Disable if not found.
+if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"check >= 0.9.4\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "check >= 0.9.4") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  	sr_have_check=yes
+	SRD_PKGLIBS_TESTS=${SRD_PKGLIBS_TESTS}${SRD_PKGLIBS_TESTS:+' '}"check >= 0.9.4"
+	sr_check_version=`$PKG_CONFIG --modversion "check >= 0.9.4" 2>&5`
+	sr_pkg_check_summary_append "check >= 0.9.4" "$sr_check_version"
 else
-  no_glib=yes
+  	sr_pkg_check_summary_append "check >= 0.9.4" no
+	sr_have_check=no sr_check_version=
 fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
+
+ if test "x$sr_have_check" = xyes; then
+  HAVE_CHECK_TRUE=
+  HAVE_CHECK_FALSE='#'
+else
+  HAVE_CHECK_TRUE='#'
+  HAVE_CHECK_FALSE=
 fi
 
-       CFLAGS="$ac_save_CFLAGS"
-       LIBS="$ac_save_LIBS"
-     fi
-  fi
-  if test "x$no_glib" = x ; then
-     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes (version $glib_config_major_version.$glib_config_minor_version.$glib_config_micro_version)" >&5
-$as_echo "yes (version $glib_config_major_version.$glib_config_minor_version.$glib_config_micro_version)" >&6; }
-     CFLAGS="$CFLAGS $GLIB_CFLAGS"; LIBS="$LIBS $GLIB_LIBS"
-  else
-     { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-     if test "$PKG_CONFIG" = "no" ; then
-       echo "*** A new enough version of pkg-config was not found."
-       echo "*** See http://www.freedesktop.org/software/pkgconfig/"
-     else
-       if test -f conf.glibtest ; then
-        :
-       else
-          echo "*** Could not run GLIB test program, checking why..."
-          ac_save_CFLAGS="$CFLAGS"
-          ac_save_LIBS="$LIBS"
-          CFLAGS="$CFLAGS $GLIB_CFLAGS"
-          LIBS="$LIBS $GLIB_LIBS"
-          cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
 
-#include <glib.h>
-#include <stdio.h>
+# Enable the C99 standard if possible, and enforce the use
+# of SRD_API to explicitly mark all public API functions.
+SRD_EXTRA_CFLAGS=
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking compiler flag for C99" >&5
+$as_echo_n "checking compiler flag for C99... " >&6; }
+sr_ccf_result=no
+sr_ccf_save_CPPFLAGS=$CPPFLAGS
+for sr_flag in -std=c99 -c99 -AC99 -qlanglvl=extc99
+do
+	CPPFLAGS="$sr_ccf_save_CPPFLAGS $sr_flag"
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
 int
 main ()
 {
- return ((glib_major_version) || (glib_minor_version) || (glib_micro_version));
+
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-   echo "*** The test program compiled, but did not run. This usually means"
-          echo "*** that the run-time linker is not finding GLIB or finding the wrong"
-          echo "*** version of GLIB. If it is not finding GLIB, you'll need to set your"
-          echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
-          echo "*** to the installed location  Also, make sure you have run ldconfig if that"
-          echo "*** is required on your system"
-	  echo "***"
-          echo "*** If you have an old version installed, it is best to remove it, although"
-          echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"
-else
-   echo "*** The test program failed to compile or link. See the file config.log for the"
-          echo "*** exact error that occured. This usually means GLIB is incorrectly installed."
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-          CFLAGS="$ac_save_CFLAGS"
-          LIBS="$ac_save_LIBS"
-       fi
-     fi
-     GLIB_CFLAGS=""
-     GLIB_LIBS=""
-     GLIB_GENMARSHAL=""
-     GOBJECT_QUERY=""
-     GLIB_MKENUMS=""
-     GLIB_COMPILE_RESOURCES=""
-     :
-  fi
-
-
-
-
-
-
-  rm -f conf.glibtest
-
-
-# Python 3 is always needed.
-# Note: We need to try a few different variants, since some systems have a
-# python3.pc file, others have a python-3.3.pc file, and so on.
-# See also: http://sigrok.org/wiki/Libsigrokdecode/Python
-CPPFLAGS_PYTHON=""
-LDFLAGS_PYTHON=""
-pyver="none"
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python3" >&5
-$as_echo_n "checking for python3... " >&6; }
-
-if test -n "$python3_CFLAGS"; then
-    pkg_cv_python3_CFLAGS="$python3_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python3 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python3 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python3_CFLAGS=`$PKG_CONFIG --cflags "python3 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python3_LIBS"; then
-    pkg_cv_python3_LIBS="$python3_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python3 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python3 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python3_LIBS=`$PKG_CONFIG --libs "python3 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python3_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python3 >= 3.2" 2>&1`
-        else
-	        python3_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python3 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python3_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python34" >&5
-$as_echo_n "checking for python34... " >&6; }
-
-if test -n "$python34_CFLAGS"; then
-    pkg_cv_python34_CFLAGS="$python34_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.4 >= 3.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.4 >= 3.4") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python34_CFLAGS=`$PKG_CONFIG --cflags "python-3.4 >= 3.4" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python34_LIBS"; then
-    pkg_cv_python34_LIBS="$python34_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.4 >= 3.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.4 >= 3.4") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python34_LIBS=`$PKG_CONFIG --libs "python-3.4 >= 3.4" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python34_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.4 >= 3.4" 2>&1`
-        else
-	        python34_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.4 >= 3.4" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python34_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python33" >&5
-$as_echo_n "checking for python33... " >&6; }
-
-if test -n "$python33_CFLAGS"; then
-    pkg_cv_python33_CFLAGS="$python33_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_CFLAGS=`$PKG_CONFIG --cflags "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python33_LIBS"; then
-    pkg_cv_python33_LIBS="$python33_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_LIBS=`$PKG_CONFIG --libs "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
+if ac_fn_c_try_compile "$LINENO"; then :
+  sr_ccf_result=$sr_flag
 fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+	test "x$sr_ccf_result" = xno || break
+done
+CPPFLAGS=$sr_ccf_save_CPPFLAGS
+if test "x$sr_ccf_result" != xno; then :
+  SRD_EXTRA_CFLAGS=${SRD_EXTRA_CFLAGS}${SRD_EXTRA_CFLAGS:+' '}$sr_ccf_result
 fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python33_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        else
-	        python33_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python33_PKG_ERRORS" >&5
-
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $sr_ccf_result" >&5
+$as_echo "$sr_ccf_result" >&6; }
 
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-else
-	python33_CFLAGS=$pkg_cv_python33_CFLAGS
-	python33_LIBS=$pkg_cv_python33_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python33_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python33_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python33" >&5
-$as_echo_n "checking for python33... " >&6; }
-
-if test -n "$python33_CFLAGS"; then
-    pkg_cv_python33_CFLAGS="$python33_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_CFLAGS=`$PKG_CONFIG --cflags "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python33_LIBS"; then
-    pkg_cv_python33_LIBS="$python33_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_LIBS=`$PKG_CONFIG --libs "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python33_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        else
-	        python33_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python33_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-else
-	python33_CFLAGS=$pkg_cv_python33_CFLAGS
-	python33_LIBS=$pkg_cv_python33_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python33_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python33_LIBS"
-fi
-else
-	python34_CFLAGS=$pkg_cv_python34_CFLAGS
-	python34_LIBS=$pkg_cv_python34_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.4`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python34_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python34_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python34" >&5
-$as_echo_n "checking for python34... " >&6; }
-
-if test -n "$python34_CFLAGS"; then
-    pkg_cv_python34_CFLAGS="$python34_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.4 >= 3.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.4 >= 3.4") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python34_CFLAGS=`$PKG_CONFIG --cflags "python-3.4 >= 3.4" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python34_LIBS"; then
-    pkg_cv_python34_LIBS="$python34_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.4 >= 3.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.4 >= 3.4") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python34_LIBS=`$PKG_CONFIG --libs "python-3.4 >= 3.4" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python34_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.4 >= 3.4" 2>&1`
-        else
-	        python34_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.4 >= 3.4" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python34_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python33" >&5
-$as_echo_n "checking for python33... " >&6; }
-
-if test -n "$python33_CFLAGS"; then
-    pkg_cv_python33_CFLAGS="$python33_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_CFLAGS=`$PKG_CONFIG --cflags "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python33_LIBS"; then
-    pkg_cv_python33_LIBS="$python33_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_LIBS=`$PKG_CONFIG --libs "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python33_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        else
-	        python33_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python33_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-else
-	python33_CFLAGS=$pkg_cv_python33_CFLAGS
-	python33_LIBS=$pkg_cv_python33_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python33_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python33_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python33" >&5
-$as_echo_n "checking for python33... " >&6; }
-
-if test -n "$python33_CFLAGS"; then
-    pkg_cv_python33_CFLAGS="$python33_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_CFLAGS=`$PKG_CONFIG --cflags "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python33_LIBS"; then
-    pkg_cv_python33_LIBS="$python33_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.3 >= 3.3\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.3 >= 3.3") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python33_LIBS=`$PKG_CONFIG --libs "python-3.3 >= 3.3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python33_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        else
-	        python33_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.3 >= 3.3" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python33_PKG_ERRORS" >&5
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for python32" >&5
-$as_echo_n "checking for python32... " >&6; }
-
-if test -n "$python32_CFLAGS"; then
-    pkg_cv_python32_CFLAGS="$python32_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_CFLAGS=`$PKG_CONFIG --cflags "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$python32_LIBS"; then
-    pkg_cv_python32_LIBS="$python32_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"python-3.2 >= 3.2\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "python-3.2 >= 3.2") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_python32_LIBS=`$PKG_CONFIG --libs "python-3.2 >= 3.2" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        python32_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        else
-	        python32_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "python-3.2 >= 3.2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$python32_PKG_ERRORS" >&5
-
-	as_fn_error $? "Package requirements (python-3.2 >= 3.2) were not met:
-
-$python32_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details." "$LINENO" 5
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-Alternatively, you may set the environment variables python32_CFLAGS
-and python32_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.
-See \`config.log' for more details" "$LINENO" 5; }
-else
-	python32_CFLAGS=$pkg_cv_python32_CFLAGS
-	python32_LIBS=$pkg_cv_python32_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"
-fi
-else
-	python33_CFLAGS=$pkg_cv_python33_CFLAGS
-	python33_LIBS=$pkg_cv_python33_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python33_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python33_LIBS"
-fi
-else
-	python34_CFLAGS=$pkg_cv_python34_CFLAGS
-	python34_LIBS=$pkg_cv_python34_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python-3.4`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python34_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python34_LIBS"
-fi
-else
-	python3_CFLAGS=$pkg_cv_python3_CFLAGS
-	python3_LIBS=$pkg_cv_python3_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	pyver=`$PKG_CONFIG --modversion python3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python3_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python3_LIBS"
-fi
-
-
-
-# We also need to find the name of the python3 executable (for 'make install').
-# Some OSes call this python3, some call it python3.2, etc. etc.
-for ac_prog in python3.4 python3.3 python3.2 python3
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_PYTHON3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$PYTHON3"; then
-  ac_cv_prog_PYTHON3="$PYTHON3" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_PYTHON3="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
 
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking compiler flag for visibility" >&5
+$as_echo_n "checking compiler flag for visibility... " >&6; }
+sr_ccf_result=no
+sr_ccf_save_CPPFLAGS=$CPPFLAGS
+for sr_flag in -fvisibility=hidden
+do
+	CPPFLAGS="$sr_ccf_save_CPPFLAGS $sr_flag"
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  sr_ccf_result=$sr_flag
 fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+	test "x$sr_ccf_result" = xno || break
+done
+CPPFLAGS=$sr_ccf_save_CPPFLAGS
+if test "x$sr_ccf_result" != xno; then :
+  SRD_EXTRA_CFLAGS=${SRD_EXTRA_CFLAGS}${SRD_EXTRA_CFLAGS:+' '}$sr_ccf_result
 fi
-PYTHON3=$ac_cv_prog_PYTHON3
-if test -n "$PYTHON3"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON3" >&5
-$as_echo "$PYTHON3" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $sr_ccf_result" >&5
+$as_echo "$sr_ccf_result" >&6; }
+
+
+
+# Select suitable compiler warning flags.
+# Check whether --enable-warnings was given.
+if test "${enable_warnings+set}" = set; then :
+  enableval=$enable_warnings; sr_enable_warnings=$enableval
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  sr_enable_warnings=max
+fi
+# Test whether the compiler accepts each flag.  Look at standard output,
+# since GCC only shows a warning message if an option is not supported.
+sr_check_compile_warning_flags() {
+	for sr_flag
+	do
+		sr_cc_out=`$sr_cc $sr_warning_flags $sr_flag -c "$sr_conftest" 2>&1 || echo failed`
+		if test "$?$sr_cc_out" = 0; then :
+  sr_warning_flags=${sr_warning_flags}${sr_warning_flags:+' '}$sr_flag
+else
+  $as_echo "$sr_cc: $sr_cc_out" >&5
 fi
+		rm -f "conftest.${OBJEXT:-o}"
+	done
+}
 
+case $ac_compile in #(
+  *'$CXXFLAGS '*) :
+    sr_lang='C++' sr_cc=$CXX sr_conftest="conftest.${ac_ext:-cc}" ;; #(
+  *'$CFLAGS '*) :
+    sr_lang=C sr_cc=$CC sr_conftest="conftest.${ac_ext:-c}" ;; #(
+  *) :
+    as_fn_error $? "current language is neither C nor C++" "$LINENO" 5 ;;
+esac
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking which $sr_lang compiler warning flags to use" >&5
+$as_echo_n "checking which $sr_lang compiler warning flags to use... " >&6; }
+sr_warning_flags=
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
 
-  test -n "$PYTHON3" && break
-done
+int main(int argc, char** argv) { return (argv != 0) ? argc : 0; }
 
-if test "x$PYTHON3" == "x"; then
-	as_fn_error $? "cannot find python3 executable." "$LINENO" 5
-fi
+_ACEOF
+case $sr_enable_warnings in #(
+  no) :
+     ;; #(
+  min) :
+    sr_check_compile_warning_flags -Wall ;; #(
+  fatal) :
+    sr_check_compile_warning_flags -Wall -Wextra -Wmissing-prototypes -Werror ;; #(
+  *) :
+    sr_check_compile_warning_flags -Wall -Wextra -Wmissing-prototypes ;;
+esac
+rm -f "$sr_conftest"
+SRD_WFLAGS=$sr_warning_flags
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ${sr_warning_flags:-none}" >&5
+$as_echo "${sr_warning_flags:-none}" >&6; }
 
 # Link against libm, this is required (among other things) by Python.
+SRD_EXTRA_LIBS=
+sr_sl_save_LIBS=$LIBS
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing pow" >&5
 $as_echo_n "checking for library containing pow... " >&6; }
 if ${ac_cv_search_pow+:} false; then :
@@ -14319,7 +13401,7 @@ for ac_lib in '' m; do
     ac_res="none required"
   else
     ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
+    LIBS="-l$ac_lib $SRD_EXTRA_LIBS $ac_func_search_save_LIBS"
   fi
   if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_search_pow=$ac_res
@@ -14346,23 +13428,239 @@ if test "$ac_res" != no; then :
 
 fi
 
+LIBS=$sr_sl_save_LIBS
+case $ac_cv_search_pow in #(
+  no*) :
+     ;; #(
+  *) :
+    SRD_EXTRA_LIBS=$ac_cv_search_pow${SRD_EXTRA_LIBS:+' '}$SRD_EXTRA_LIBS ;;
+esac
+
+
+# Check whether --enable-largefile was given.
+if test "${enable_largefile+set}" = set; then :
+  enableval=$enable_largefile;
+fi
+
+if test "$enable_largefile" != no; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5
+$as_echo_n "checking for special C compiler options needed for large files... " >&6; }
+if ${ac_cv_sys_largefile_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_sys_largefile_CC=no
+     if test "$GCC" != yes; then
+       ac_save_CC=$CC
+       while :; do
+	 # IRIX 6.2 and later do not support large files by default,
+	 # so use the C compiler's -n32 option if that helps.
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 CC="$CC -n32"
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_largefile_CC=' -n32'; break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 break
+       done
+       CC=$ac_save_CC
+       rm -f conftest.$ac_ext
+    fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5
+$as_echo "$ac_cv_sys_largefile_CC" >&6; }
+  if test "$ac_cv_sys_largefile_CC" != no; then
+    CC=$CC$ac_cv_sys_largefile_CC
+  fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5
+$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; }
+if ${ac_cv_sys_file_offset_bits+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=no; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _FILE_OFFSET_BITS 64
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=64; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_file_offset_bits=unknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5
+$as_echo "$ac_cv_sys_file_offset_bits" >&6; }
+case $ac_cv_sys_file_offset_bits in #(
+  no | unknown) ;;
+  *)
+cat >>confdefs.h <<_ACEOF
+#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  if test $ac_cv_sys_file_offset_bits = unknown; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5
+$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; }
+if ${ac_cv_sys_large_files+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=no; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _LARGE_FILES 1
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
+		       && LARGE_OFF_T % 2147483647 == 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=1; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_large_files=unknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5
+$as_echo "$ac_cv_sys_large_files" >&6; }
+case $ac_cv_sys_large_files in #(
+  no | unknown) ;;
+  *)
+cat >>confdefs.h <<_ACEOF
+#define _LARGE_FILES $ac_cv_sys_large_files
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  fi
+
+
+fi
+
+
+##############################
+##  Finalize configuration  ##
+##############################
+
 
-# The Check unit testing framework is optional. Disable if not found.
+
+# Retrieve the compile and link flags for all modules combined.
+# Also, bail out at this point if any module dependency is not met.
 
 pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for check" >&5
-$as_echo_n "checking for check... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for LIBSIGROKDECODE" >&5
+$as_echo_n "checking for LIBSIGROKDECODE... " >&6; }
 
-if test -n "$check_CFLAGS"; then
-    pkg_cv_check_CFLAGS="$check_CFLAGS"
+if test -n "$LIBSIGROKDECODE_CFLAGS"; then
+    pkg_cv_LIBSIGROKDECODE_CFLAGS="$LIBSIGROKDECODE_CFLAGS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"check >= 0.9.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "check >= 0.9.4") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"glib-2.0 >= 2.28.0 \$SRD_PKGLIBS\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "glib-2.0 >= 2.28.0 $SRD_PKGLIBS") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_check_CFLAGS=`$PKG_CONFIG --cflags "check >= 0.9.4" 2>/dev/null`
+  pkg_cv_LIBSIGROKDECODE_CFLAGS=`$PKG_CONFIG --cflags "glib-2.0 >= 2.28.0 $SRD_PKGLIBS" 2>/dev/null`
 		      test "x$?" != "x0" && pkg_failed=yes
 else
   pkg_failed=yes
@@ -14370,16 +13668,16 @@ fi
  else
     pkg_failed=untried
 fi
-if test -n "$check_LIBS"; then
-    pkg_cv_check_LIBS="$check_LIBS"
+if test -n "$LIBSIGROKDECODE_LIBS"; then
+    pkg_cv_LIBSIGROKDECODE_LIBS="$LIBSIGROKDECODE_LIBS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"check >= 0.9.4\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "check >= 0.9.4") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"glib-2.0 >= 2.28.0 \$SRD_PKGLIBS\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "glib-2.0 >= 2.28.0 $SRD_PKGLIBS") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_check_LIBS=`$PKG_CONFIG --libs "check >= 0.9.4" 2>/dev/null`
+  pkg_cv_LIBSIGROKDECODE_LIBS=`$PKG_CONFIG --libs "glib-2.0 >= 2.28.0 $SRD_PKGLIBS" 2>/dev/null`
 		      test "x$?" != "x0" && pkg_failed=yes
 else
   pkg_failed=yes
@@ -14400,52 +13698,60 @@ else
         _pkg_short_errors_supported=no
 fi
         if test $_pkg_short_errors_supported = yes; then
-	        check_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "check >= 0.9.4" 2>&1`
+	        LIBSIGROKDECODE_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "glib-2.0 >= 2.28.0 $SRD_PKGLIBS" 2>&1`
         else
-	        check_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "check >= 0.9.4" 2>&1`
+	        LIBSIGROKDECODE_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "glib-2.0 >= 2.28.0 $SRD_PKGLIBS" 2>&1`
         fi
 	# Put the nasty error message in config.log where it belongs
-	echo "$check_PKG_ERRORS" >&5
+	echo "$LIBSIGROKDECODE_PKG_ERRORS" >&5
+
+	as_fn_error $? "Package requirements (glib-2.0 >= 2.28.0 $SRD_PKGLIBS) were not met:
+
+$LIBSIGROKDECODE_PKG_ERRORS
+
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
 
-	have_check="no"
+Alternatively, you may set the environment variables LIBSIGROKDECODE_CFLAGS
+and LIBSIGROKDECODE_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details." "$LINENO" 5
 elif test $pkg_failed = untried; then
      	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
-	have_check="no"
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
+
+Alternatively, you may set the environment variables LIBSIGROKDECODE_CFLAGS
+and LIBSIGROKDECODE_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details.
+
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.
+See \`config.log' for more details" "$LINENO" 5; }
 else
-	check_CFLAGS=$pkg_cv_check_CFLAGS
-	check_LIBS=$pkg_cv_check_LIBS
+	LIBSIGROKDECODE_CFLAGS=$pkg_cv_LIBSIGROKDECODE_CFLAGS
+	LIBSIGROKDECODE_LIBS=$pkg_cv_LIBSIGROKDECODE_LIBS
         { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
-	have_check="yes"; CFLAGS="$CFLAGS $check_CFLAGS";
-	LIBS="$LIBS $check_LIBS"
-fi
- if test x"$have_check" = "xyes"; then
-  HAVE_CHECK_TRUE=
-  HAVE_CHECK_FALSE='#'
-else
-  HAVE_CHECK_TRUE='#'
-  HAVE_CHECK_FALSE=
-fi
 
-
-# libsigrok is optional (only used for the protocol decoder test framework).
-# Disable if not found.
+fi
 
 pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for libsigrok" >&5
-$as_echo_n "checking for libsigrok... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for TESTS" >&5
+$as_echo_n "checking for TESTS... " >&6; }
 
-if test -n "$libsigrok_CFLAGS"; then
-    pkg_cv_libsigrok_CFLAGS="$libsigrok_CFLAGS"
+if test -n "$TESTS_CFLAGS"; then
+    pkg_cv_TESTS_CFLAGS="$TESTS_CFLAGS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libsigrok >= 0.3.0\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libsigrok >= 0.3.0") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"\$SRD_PKGLIBS_TESTS glib-2.0 \$SRD_PKGLIBS\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_libsigrok_CFLAGS=`$PKG_CONFIG --cflags "libsigrok >= 0.3.0" 2>/dev/null`
+  pkg_cv_TESTS_CFLAGS=`$PKG_CONFIG --cflags "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS" 2>/dev/null`
 		      test "x$?" != "x0" && pkg_failed=yes
 else
   pkg_failed=yes
@@ -14453,16 +13759,16 @@ fi
  else
     pkg_failed=untried
 fi
-if test -n "$libsigrok_LIBS"; then
-    pkg_cv_libsigrok_LIBS="$libsigrok_LIBS"
+if test -n "$TESTS_LIBS"; then
+    pkg_cv_TESTS_LIBS="$TESTS_LIBS"
  elif test -n "$PKG_CONFIG"; then
     if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libsigrok >= 0.3.0\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "libsigrok >= 0.3.0") 2>&5
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"\$SRD_PKGLIBS_TESTS glib-2.0 \$SRD_PKGLIBS\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS") 2>&5
   ac_status=$?
   $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; then
-  pkg_cv_libsigrok_LIBS=`$PKG_CONFIG --libs "libsigrok >= 0.3.0" 2>/dev/null`
+  pkg_cv_TESTS_LIBS=`$PKG_CONFIG --libs "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS" 2>/dev/null`
 		      test "x$?" != "x0" && pkg_failed=yes
 else
   pkg_failed=yes
@@ -14483,66 +13789,49 @@ else
         _pkg_short_errors_supported=no
 fi
         if test $_pkg_short_errors_supported = yes; then
-	        libsigrok_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libsigrok >= 0.3.0" 2>&1`
+	        TESTS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS" 2>&1`
         else
-	        libsigrok_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libsigrok >= 0.3.0" 2>&1`
+	        TESTS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS" 2>&1`
         fi
 	# Put the nasty error message in config.log where it belongs
-	echo "$libsigrok_PKG_ERRORS" >&5
+	echo "$TESTS_PKG_ERRORS" >&5
+
+	as_fn_error $? "Package requirements ($SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS) were not met:
+
+$TESTS_PKG_ERRORS
 
-	build_runtc="no"
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
+
+Alternatively, you may set the environment variables TESTS_CFLAGS
+and TESTS_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details." "$LINENO" 5
 elif test $pkg_failed = untried; then
      	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
-	build_runtc="no"
-else
-	libsigrok_CFLAGS=$pkg_cv_libsigrok_CFLAGS
-	libsigrok_LIBS=$pkg_cv_libsigrok_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	LIBSIGROK_CFLAGS="$libsigrok_CFLAGS"; LIBSIGROK_LIBS="$libsigrok_LIBS"
-fi
-
-
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
 
-# Checks for header files.
-# These are already checked: inttypes.h stdint.h stdlib.h string.h unistd.h.
-ac_fn_c_check_header_mongrel "$LINENO" "sys/resource.h" "ac_cv_header_sys_resource_h" "$ac_includes_default"
-if test "x$ac_cv_header_sys_resource_h" = xyes; then :
+Alternatively, you may set the environment variables TESTS_CFLAGS
+and TESTS_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details.
 
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.
+See \`config.log' for more details" "$LINENO" 5; }
 else
-  build_runtc="no"
-fi
-
-
-
-DECODERS_DIR="$datadir/libsigrokdecode/decoders"
-
-MAKEFLAGS='--no-print-directory'
-
-AM_LIBTOOLFLAGS='--silent'
-
-
-SRD_PACKAGE_VERSION_MAJOR=0
-SRD_PACKAGE_VERSION_MINOR=3
-SRD_PACKAGE_VERSION_MICRO=0
-SRD_PACKAGE_VERSION=0.3.0
-
-
-
-
-
+	TESTS_CFLAGS=$pkg_cv_TESTS_CFLAGS
+	TESTS_LIBS=$pkg_cv_TESTS_LIBS
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 
- if test x"$build_runtc" = "xyes"; then
-  BUILD_RUNTC_TRUE=
-  BUILD_RUNTC_FALSE='#'
-else
-  BUILD_RUNTC_TRUE='#'
-  BUILD_RUNTC_FALSE=
 fi
 
+srd_glib_version=`$PKG_CONFIG --modversion glib-2.0 2>&5`
 
-ac_config_files="$ac_config_files Makefile version.h libsigrokdecode.pc"
+ac_config_files="$ac_config_files Makefile libsigrokdecode.pc"
 
 
 cat >confcache <<\_ACEOF
@@ -14682,12 +13971,12 @@ if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then
   as_fn_error $? "conditional \"am__fastdepCC\" was never defined.
 Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
-if test -z "${HAVE_CHECK_TRUE}" && test -z "${HAVE_CHECK_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_CHECK\" was never defined.
+if test -z "${WIN32_TRUE}" && test -z "${WIN32_FALSE}"; then
+  as_fn_error $? "conditional \"WIN32\" was never defined.
 Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
-if test -z "${BUILD_RUNTC_TRUE}" && test -z "${BUILD_RUNTC_FALSE}"; then
-  as_fn_error $? "conditional \"BUILD_RUNTC\" was never defined.
+if test -z "${HAVE_CHECK_TRUE}" && test -z "${HAVE_CHECK_FALSE}"; then
+  as_fn_error $? "conditional \"HAVE_CHECK\" was never defined.
 Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 
@@ -15087,7 +14376,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by libsigrokdecode $as_me 0.3.0, which was
+This file was extended by libsigrokdecode $as_me 0.4.1, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -15154,7 +14443,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-libsigrokdecode config.status 0.3.0
+libsigrokdecode config.status 0.4.1
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
@@ -15289,6 +14578,7 @@ enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`'
 enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`'
 pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`'
 enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`'
+shared_archive_member_spec='`$ECHO "$shared_archive_member_spec" | $SED "$delay_single_quote_subst"`'
 SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`'
 ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`'
 PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`'
@@ -15338,10 +14628,13 @@ compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`'
 GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`'
 lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`'
 lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_import='`$ECHO "$lt_cv_sys_global_symbol_to_import" | $SED "$delay_single_quote_subst"`'
 lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`'
 lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`'
+lt_cv_nm_interface='`$ECHO "$lt_cv_nm_interface" | $SED "$delay_single_quote_subst"`'
 nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`'
 lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`'
+lt_cv_truncate_bin='`$ECHO "$lt_cv_truncate_bin" | $SED "$delay_single_quote_subst"`'
 objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`'
 MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`'
 lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`'
@@ -15406,7 +14699,8 @@ finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`'
 finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`'
 hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`'
 sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`'
-sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`'
+configure_time_dlsearch_path='`$ECHO "$configure_time_dlsearch_path" | $SED "$delay_single_quote_subst"`'
+configure_time_lt_sys_library_path='`$ECHO "$configure_time_lt_sys_library_path" | $SED "$delay_single_quote_subst"`'
 hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`'
 enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`'
 enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`'
@@ -15457,9 +14751,12 @@ CFLAGS \
 compiler \
 lt_cv_sys_global_symbol_pipe \
 lt_cv_sys_global_symbol_to_cdecl \
+lt_cv_sys_global_symbol_to_import \
 lt_cv_sys_global_symbol_to_c_name_address \
 lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \
+lt_cv_nm_interface \
 nm_file_list_spec \
+lt_cv_truncate_bin \
 lt_prog_compiler_no_builtin_flag \
 lt_prog_compiler_pic \
 lt_prog_compiler_wl \
@@ -15494,7 +14791,7 @@ old_striplib \
 striplib; do
     case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[\\\\\\\`\\"\\\$]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes
       ;;
     *)
       eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
@@ -15521,10 +14818,11 @@ postinstall_cmds \
 postuninstall_cmds \
 finish_cmds \
 sys_lib_search_path_spec \
-sys_lib_dlsearch_path_spec; do
+configure_time_dlsearch_path \
+configure_time_lt_sys_library_path; do
     case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[\\\\\\\`\\"\\\$]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes
       ;;
     *)
       eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
@@ -15533,19 +14831,16 @@ sys_lib_dlsearch_path_spec; do
 done
 
 ac_aux_dir='$ac_aux_dir'
-xsi_shell='$xsi_shell'
-lt_shell_append='$lt_shell_append'
 
-# See if we are running on zsh, and set the options which allow our
+# See if we are running on zsh, and set the options that allow our
 # commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
+if test -n "\${ZSH_VERSION+set}"; then
    setopt NO_GLOB_SUBST
 fi
 
 
     PACKAGE='$PACKAGE'
     VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
     RM='$RM'
     ofile='$ofile'
 
@@ -15561,10 +14856,10 @@ for ac_config_target in $ac_config_targets
 do
   case $ac_config_target in
     "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+    "version.h") CONFIG_HEADERS="$CONFIG_HEADERS version.h" ;;
     "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
     "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
     "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "version.h") CONFIG_FILES="$CONFIG_FILES version.h" ;;
     "libsigrokdecode.pc") CONFIG_FILES="$CONFIG_FILES libsigrokdecode.pc" ;;
 
   *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
@@ -16256,55 +15551,52 @@ $as_echo X"$file" |
  ;;
     "libtool":C)
 
-    # See if we are running on zsh, and set the options which allow our
+    # See if we are running on zsh, and set the options that allow our
     # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
+    if test -n "${ZSH_VERSION+set}"; then
       setopt NO_GLOB_SUBST
     fi
 
-    cfgfile="${ofile}T"
+    cfgfile=${ofile}T
     trap "$RM \"$cfgfile\"; exit 1" 1 2 15
     $RM "$cfgfile"
 
     cat <<_LT_EOF >> "$cfgfile"
 #! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# Generated automatically by $as_me ($PACKAGE) $VERSION
 # NOTE: Changes made to this file will be lost: look at ltmain.sh.
+
+# Provide generalized library-building support services.
+# Written by Gordon Matzigkeit, 1996
+
+# Copyright (C) 2014 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# GNU Libtool 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 of the License, or
+# (at your option) any later version.
 #
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool 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.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program or library that is built
+# using GNU Libtool, you may include this file under the  same
+# distribution terms that you use for the rest of that program.
 #
-# GNU Libtool is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 
 # The names of the tagged configurations supported by this script.
-available_tags=""
+available_tags=''
+
+# Configured defaults for sys_lib_dlsearch_path munging.
+: \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"}
 
 # ### BEGIN LIBTOOL CONFIG
 
@@ -16324,6 +15616,9 @@ pic_mode=$pic_mode
 # Whether or not to optimize for fast installation.
 fast_install=$enable_fast_install
 
+# Shared archive member basename,for filename based shared library versioning on AIX.
+shared_archive_member_spec=$shared_archive_member_spec
+
 # Shell to use when invoking shell scripts.
 SHELL=$lt_SHELL
 
@@ -16441,18 +15736,27 @@ global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
 # Transform the output of nm in a proper C declaration.
 global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
 
+# Transform the output of nm into a list of symbols to manually relocate.
+global_symbol_to_import=$lt_lt_cv_sys_global_symbol_to_import
+
 # Transform the output of nm in a C name address pair.
 global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
 
 # Transform the output of nm in a C name address pair when lib prefix is needed.
 global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix
 
+# The name lister interface.
+nm_interface=$lt_lt_cv_nm_interface
+
 # Specify filename containing input files for \$NM.
 nm_file_list_spec=$lt_nm_file_list_spec
 
-# The root where to search for dependent libraries,and in which our libraries should be installed.
+# The root where to search for dependent libraries,and where our libraries should be installed.
 lt_sysroot=$lt_sysroot
 
+# Command to truncate a binary pipe.
+lt_truncate_bin=$lt_lt_cv_truncate_bin
+
 # The name of the directory that contains temporary libtool files.
 objdir=$objdir
 
@@ -16543,8 +15847,11 @@ hardcode_into_libs=$hardcode_into_libs
 # Compile-time system search path for libraries.
 sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
 
-# Run-time system search path for libraries.
-sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
+# Detected run-time system search path for libraries.
+sys_lib_dlsearch_path_spec=$lt_configure_time_dlsearch_path
+
+# Explicit LT_SYS_LIBRARY_PATH set during ./configure time.
+configure_time_lt_sys_library_path=$lt_configure_time_lt_sys_library_path
 
 # Whether dlopen is supported.
 dlopen_support=$enable_dlopen
@@ -16637,13 +15944,13 @@ hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec
 # Whether we need a single "-rpath" flag with a separated argument.
 hardcode_libdir_separator=$lt_hardcode_libdir_separator
 
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes
 # DIR into the resulting binary.
 hardcode_direct=$hardcode_direct
 
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes
 # DIR into the resulting binary and the resulting library dependency is
-# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
+# "absolute",i.e impossible to change by setting \$shlibpath_var if the
 # library is relocated.
 hardcode_direct_absolute=$hardcode_direct_absolute
 
@@ -16695,13 +16002,72 @@ hardcode_action=$hardcode_action
 
 _LT_EOF
 
+    cat <<'_LT_EOF' >> "$cfgfile"
+
+# ### BEGIN FUNCTIONS SHARED WITH CONFIGURE
+
+# func_munge_path_list VARIABLE PATH
+# -----------------------------------
+# VARIABLE is name of variable containing _space_ separated list of
+# directories to be munged by the contents of PATH, which is string
+# having a format:
+# "DIR[:DIR]:"
+#       string "DIR[ DIR]" will be prepended to VARIABLE
+# ":DIR[:DIR]"
+#       string "DIR[ DIR]" will be appended to VARIABLE
+# "DIRP[:DIRP]::[DIRA:]DIRA"
+#       string "DIRP[ DIRP]" will be prepended to VARIABLE and string
+#       "DIRA[ DIRA]" will be appended to VARIABLE
+# "DIR[:DIR]"
+#       VARIABLE will be replaced by "DIR[ DIR]"
+func_munge_path_list ()
+{
+    case x$2 in
+    x)
+        ;;
+    *:)
+        eval $1=\"`$ECHO $2 | $SED 's/:/ /g'` \$$1\"
+        ;;
+    x:*)
+        eval $1=\"\$$1 `$ECHO $2 | $SED 's/:/ /g'`\"
+        ;;
+    *::*)
+        eval $1=\"\$$1\ `$ECHO $2 | $SED -e 's/.*:://' -e 's/:/ /g'`\"
+        eval $1=\"`$ECHO $2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \$$1\"
+        ;;
+    *)
+        eval $1=\"`$ECHO $2 | $SED 's/:/ /g'`\"
+        ;;
+    esac
+}
+
+
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+func_cc_basename ()
+{
+    for cc_temp in $*""; do
+      case $cc_temp in
+        compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+        distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+        \-*) ;;
+        *) break;;
+      esac
+    done
+    func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+}
+
+
+# ### END FUNCTIONS SHARED WITH CONFIGURE
+
+_LT_EOF
+
   case $host_os in
   aix3*)
     cat <<\_LT_EOF >> "$cfgfile"
 # AIX sometimes has problems with the GCC collect2 program.  For some
 # reason, if we set the COLLECT_NAMES environment variable, the problems
 # vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
+if test set != "${COLLECT_NAMES+set}"; then
   COLLECT_NAMES=
   export COLLECT_NAMES
 fi
@@ -16710,7 +16076,7 @@ _LT_EOF
   esac
 
 
-ltmain="$ac_aux_dir/ltmain.sh"
+ltmain=$ac_aux_dir/ltmain.sh
 
 
   # We use sed instead of cat because bash on DJGPP gets confused if
@@ -16720,165 +16086,6 @@ ltmain="$ac_aux_dir/ltmain.sh"
   sed '$q' "$ltmain" >> "$cfgfile" \
      || (rm -f "$cfgfile"; exit 1)
 
-  if test x"$xsi_shell" = xyes; then
-  sed -e '/^func_dirname ()$/,/^} # func_dirname /c\
-func_dirname ()\
-{\
-\    case ${1} in\
-\      */*) func_dirname_result="${1%/*}${2}" ;;\
-\      *  ) func_dirname_result="${3}" ;;\
-\    esac\
-} # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_basename ()$/,/^} # func_basename /c\
-func_basename ()\
-{\
-\    func_basename_result="${1##*/}"\
-} # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\
-func_dirname_and_basename ()\
-{\
-\    case ${1} in\
-\      */*) func_dirname_result="${1%/*}${2}" ;;\
-\      *  ) func_dirname_result="${3}" ;;\
-\    esac\
-\    func_basename_result="${1##*/}"\
-} # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_stripname ()$/,/^} # func_stripname /c\
-func_stripname ()\
-{\
-\    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\
-\    # positional parameters, so assign one to ordinary parameter first.\
-\    func_stripname_result=${3}\
-\    func_stripname_result=${func_stripname_result#"${1}"}\
-\    func_stripname_result=${func_stripname_result%"${2}"}\
-} # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\
-func_split_long_opt ()\
-{\
-\    func_split_long_opt_name=${1%%=*}\
-\    func_split_long_opt_arg=${1#*=}\
-} # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\
-func_split_short_opt ()\
-{\
-\    func_split_short_opt_arg=${1#??}\
-\    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\
-} # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\
-func_lo2o ()\
-{\
-\    case ${1} in\
-\      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\
-\      *)    func_lo2o_result=${1} ;;\
-\    esac\
-} # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_xform ()$/,/^} # func_xform /c\
-func_xform ()\
-{\
-    func_xform_result=${1%.*}.lo\
-} # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_arith ()$/,/^} # func_arith /c\
-func_arith ()\
-{\
-    func_arith_result=$(( $* ))\
-} # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_len ()$/,/^} # func_len /c\
-func_len ()\
-{\
-    func_len_result=${#1}\
-} # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-fi
-
-if test x"$lt_shell_append" = xyes; then
-  sed -e '/^func_append ()$/,/^} # func_append /c\
-func_append ()\
-{\
-    eval "${1}+=\\${2}"\
-} # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\
-func_append_quoted ()\
-{\
-\    func_quote_for_eval "${2}"\
-\    eval "${1}+=\\\\ \\$func_quote_for_eval_result"\
-} # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  # Save a `func_append' function call where possible by direct use of '+='
-  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-else
-  # Save a `func_append' function call even when '+=' is not available
-  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-fi
-
-if test x"$_lt_function_replace_fail" = x":"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5
-$as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;}
-fi
-
-
    mv -f "$cfgfile" "$ofile" ||
     (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
   chmod +x "$ofile"
@@ -16923,41 +16130,25 @@ $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
 fi
 
 
-echo
-echo "libsigrokdecode configuration summary:"
-echo
-echo "  - Package version (major.minor.micro):    $SRD_PACKAGE_VERSION"
-echo "  - Library version (current:revision:age): $SRD_LIB_VERSION"
-echo "  - Prefix: $prefix"
-echo "  - Building on: $build"
-echo "  - Building for: $host"
-echo
-echo "Detected libraries:"
-echo
-
-if test "x$pyver" = "xnone"; then
-	echo "  - (REQUIRED) python >= 3.2: no"
-else
-	echo "  - (REQUIRED) python >= 3.2: yes ($pyver)"
-fi
+cat >&6 <<_EOF
 
-# Note: This only works for libs with pkg-config integration.
-for lib in "glib-2.0 >= 2.24.0" "check >= 0.9.4" "libsigrok >= 0.3.0"; do
-	optional="OPTIONAL"
-	if test "x$lib" = "xglib-2.0 >= 2.24.0"; then optional="REQUIRED"; fi
-	if `$PKG_CONFIG --exists $lib`; then
-		ver=`$PKG_CONFIG --modversion $lib`
-		answer="yes ($ver)"
-	else
-		answer="no"
-	fi
-	echo "  - ($optional) $lib: $answer"
-done
+libsigrokdecode configuration summary:
+ - Package version................. $SRD_PACKAGE_VERSION
+ - Library ABI version............. $SRD_LIB_VERSION
+ - Prefix.......................... $prefix
+ - Building on..................... $build
+ - Building for.................... $host
 
-echo
-echo "Enabled features:"
-echo
-echo "  - (OPTIONAL) Library unit test framework support: $have_check"
-echo "  - (OPTIONAL) Protocol decoder test framework support: $build_runtc"
-echo
+Compile configuration:
+ - C compiler...................... $CC
+ - C compiler version.............. $srd_cc_version
+ - C compiler flags................ $CFLAGS
+ - Additional C compiler flags..... $SRD_EXTRA_CFLAGS
+ - C compiler warnings............. $SRD_WFLAGS
 
+Detected libraries (required):
+ - glib-2.0 >= 2.28.0.............. $srd_glib_version
+$srd_pkglibs_summary
+Detected libraries (optional):
+$srd_pkglibs_opt_summary
+_EOF
diff --git a/configure.ac b/configure.ac
index 1808751..46ddd95 100644
--- a/configure.ac
+++ b/configure.ac
@@ -21,183 +21,144 @@
 AC_PREREQ([2.63])
 
 # libsigrokdecode package version number (NOT the same as shared lib version!).
-m4_define([srd_package_version_major], [0])
-m4_define([srd_package_version_minor], [3])
-m4_define([srd_package_version_micro], [0])
-m4_define([srd_package_version], [srd_package_version_major.srd_package_version_minor.srd_package_version_micro])
-
-AC_INIT([libsigrokdecode], [srd_package_version],
+AC_INIT([libsigrokdecode], [0.4.1],
 	[sigrok-devel at lists.sourceforge.net], [libsigrokdecode],
 	[http://www.sigrok.org])
-AC_CONFIG_HEADER([config.h])
-AC_CONFIG_MACRO_DIR([autostuff])
+AC_CONFIG_MACRO_DIR([m4])
 AC_CONFIG_AUX_DIR([autostuff])
+AC_CONFIG_HEADERS([config.h version.h])
 
 # We require at least automake 1.11 (needed for 'silent rules').
-AM_INIT_AUTOMAKE([1.11 -Wall -Werror subdir-objects check-news color-tests])
-m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
+AM_INIT_AUTOMAKE([1.11 -Wall -Werror no-define subdir-objects check-news color-tests])
+AM_SILENT_RULES([yes])
 m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
 
-AH_TOP([#ifndef SRD_CONFIG_H
-#define SRD_CONFIG_H    /* To stop multiple inclusions. */])
-AH_BOTTOM([#endif /* SRD_CONFIG_H */])
-
-# Enable more compiler warnings via -Wall and -Wextra. Add -fvisibility=hidden
-# and enforce use of SRD_API to explicitly mark all public API functions.
-CFLAGS="$CFLAGS -Wall -Wextra -Wmissing-prototypes -fvisibility=hidden"
+AC_CANONICAL_HOST
 
 # Checks for programs.
 AC_PROG_CC
-AC_PROG_CPP
 AC_PROG_INSTALL
 AC_PROG_LN_S
 
 # Required for per-target flags or subdir-objects with C sources.
 AM_PROG_CC_C_O
 
+# Set the standard the C library headers should conform to.
+AH_VERBATIM([_POSIX_C_SOURCE], [/* The targeted POSIX standard. */
+#ifndef _POSIX_C_SOURCE
+# define _POSIX_C_SOURCE 200112L
+#endif])
+
+# Get compiler versions.
+SR_PROG_VERSION([$CC], [srd_cc_version])
+
 # Initialize libtool.
 LT_INIT
 
-# Initialize pkg-config.
-# We require at least 0.22, as "Requires.private" behaviour changed there.
-PKG_PROG_PKG_CONFIG([0.22])
+# Set up the libsigrokdecode version defines.
+SR_PKG_VERSION_SET([SRD_PACKAGE_VERSION], [AC_PACKAGE_VERSION])
 
 # Library version for libsigrokdecode (NOT the same as the package version).
 # Carefully read the libtool docs before updating these numbers!
 # The algorithm for determining which number to change (and how) is nontrivial!
 # http://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info
-SRD_LIB_VERSION_CURRENT=2
-SRD_LIB_VERSION_REVISION=0
-SRD_LIB_VERSION_AGE=0
-SRD_LIB_VERSION="$SRD_LIB_VERSION_CURRENT:$SRD_LIB_VERSION_REVISION:$SRD_LIB_VERSION_AGE"
-SRD_LIB_LDFLAGS="-version-info $SRD_LIB_VERSION"
-AC_SUBST(SRD_LIB_VERSION_CURRENT)
-AC_SUBST(SRD_LIB_VERSION_REVISION)
-AC_SUBST(SRD_LIB_VERSION_AGE)
-AC_SUBST(SRD_LIB_VERSION)
-AC_SUBST(SRD_LIB_LDFLAGS)
-
-# Assume we can build tests/runtc unless proven otherwise.
-build_runtc="yes"
-
-# Checks for libraries.
-
-# libglib-2.0 is always needed.
-# Note: glib-2.0 is part of the libsigrokdecode API
-# (hard pkg-config requirement).
-AM_PATH_GLIB_2_0([2.24.0],
-        [CFLAGS="$CFLAGS $GLIB_CFLAGS"; LIBS="$LIBS $GLIB_LIBS"])
+# Format: current:revision:age.
+SR_LIB_VERSION_SET([SRD_LIB_VERSION], [3:1:0])
+
+AM_CONDITIONAL([WIN32], [test -z "${host_os##mingw*}" || test -z "${host_os##cygwin*}"])
+
+############################
+##  Package dependencies  ##
+############################
+
+# Initialize pkg-config.
+# We require at least 0.22, as "Requires.private" behaviour changed there.
+PKG_PROG_PKG_CONFIG([0.22])
+
+# Collect the pkg-config module names of all dependencies in SRD_PKGLIBS.
+# These are used to derive the compiler flags and for the "Requires.private"
+# field in the generated libsigrokdecode.pc file.
+SRD_PKGLIBS=
+SRD_PKGLIBS_TESTS=
+
+# Keep track of all checked modules so we can list them at the end.
+SR_PKG_CHECK_SUMMARY([srd_pkglibs_summary])
 
 # Python 3 is always needed.
-# Note: We need to try a few different variants, since some systems have a
-# python3.pc file, others have a python-3.3.pc file, and so on.
-# See also: http://sigrok.org/wiki/Libsigrokdecode/Python
-CPPFLAGS_PYTHON=""
-LDFLAGS_PYTHON=""
-pyver="none"
-PKG_CHECK_MODULES([python3], [python3 >= 3.2],
-	[pyver=`$PKG_CONFIG --modversion python3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python3_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python3_LIBS"],
-[PKG_CHECK_MODULES([python34], [python-3.4 >= 3.4],
-	[pyver=`$PKG_CONFIG --modversion python-3.4`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python34_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python34_LIBS"],
-[PKG_CHECK_MODULES([python33], [python-3.3 >= 3.3],
-	[pyver=`$PKG_CONFIG --modversion python-3.3`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python33_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python33_LIBS"],
-[PKG_CHECK_MODULES([python32], [python-3.2 >= 3.2],
-	[pyver=`$PKG_CONFIG --modversion python-3.2`;
-	CPPFLAGS_PYTHON="$CPPFLAGS_PYTHON $python32_CFLAGS";
-	LDFLAGS_PYTHON="$LDFLAGS_PYTHON $python32_LIBS"],
-)])])])
-AC_SUBST(CPPFLAGS_PYTHON)
-AC_SUBST(LDFLAGS_PYTHON)
+SR_PKG_CHECK([python3], [SRD_PKGLIBS],
+	[python3 >= 3.2], [python-3.6 >= 3.6], [python-3.5 >= 3.5], [python-3.4 >= 3.4], [python-3.3 >= 3.3], [python-3.2 >= 3.2])
+AS_IF([test "x$sr_have_python3" = xno],
+	[AC_MSG_ERROR([Cannot find Python 3 development headers.])])
 
 # We also need to find the name of the python3 executable (for 'make install').
 # Some OSes call this python3, some call it python3.2, etc. etc.
-AC_CHECK_PROGS([PYTHON3], [python3.4 python3.3 python3.2 python3])
-if test "x$PYTHON3" == "x"; then
-	AC_MSG_ERROR([cannot find python3 executable.])
-fi
+AC_ARG_VAR([PYTHON3], [Python 3 interpreter])
+AC_CHECK_PROGS([PYTHON3], [python3.6 python3.5 python3.4 python3.3 python3.2 python3])
+AS_IF([test "x$PYTHON3" = x],
+	[AC_MSG_ERROR([Cannot find Python 3 interpreter.])])
 
-# Link against libm, this is required (among other things) by Python.
-AC_SEARCH_LIBS([pow], [m])
+######################
+##  Feature checks  ##
+######################
+
+# Keep track of all checked modules so we can list them at the end.
+SR_PKG_CHECK_SUMMARY([srd_pkglibs_opt_summary])
 
 # The Check unit testing framework is optional. Disable if not found.
-PKG_CHECK_MODULES([check], [check >= 0.9.4],
-	[have_check="yes"; CFLAGS="$CFLAGS $check_CFLAGS";
-	LIBS="$LIBS $check_LIBS"], [have_check="no"])
-AM_CONDITIONAL(HAVE_CHECK, test x"$have_check" = "xyes")
+SR_PKG_CHECK([check], [SRD_PKGLIBS_TESTS], [check >= 0.9.4])
+AM_CONDITIONAL([HAVE_CHECK], [test "x$sr_have_check" = xyes])
 
-# libsigrok is optional (only used for the protocol decoder test framework).
-# Disable if not found.
-PKG_CHECK_MODULES([libsigrok], [libsigrok >= 0.3.0],
-	[LIBSIGROK_CFLAGS="$libsigrok_CFLAGS"; LIBSIGROK_LIBS="$libsigrok_LIBS"],
-	[build_runtc="no"])
-AC_SUBST([LIBSIGROK_CFLAGS])
-AC_SUBST([LIBSIGROK_LIBS])
+# Enable the C99 standard if possible, and enforce the use
+# of SRD_API to explicitly mark all public API functions.
+SRD_EXTRA_CFLAGS=
+SR_CHECK_COMPILE_FLAGS([SRD_EXTRA_CFLAGS], [C99], [-std=c99 -c99 -AC99 -qlanglvl=extc99])
+SR_CHECK_COMPILE_FLAGS([SRD_EXTRA_CFLAGS], [visibility], [-fvisibility=hidden])
 
-# Checks for header files.
-# These are already checked: inttypes.h stdint.h stdlib.h string.h unistd.h.
-AC_CHECK_HEADER([sys/resource.h], [], [build_runtc="no"])
+# Select suitable compiler warning flags.
+SR_ARG_ENABLE_WARNINGS([SRD_WFLAGS], [-Wall], [-Wall -Wextra -Wmissing-prototypes])
 
-AC_SUBST(DECODERS_DIR, "$datadir/libsigrokdecode/decoders")
-AC_SUBST(MAKEFLAGS, '--no-print-directory')
-AC_SUBST(AM_LIBTOOLFLAGS, '--silent')
+# Link against libm, this is required (among other things) by Python.
+SRD_EXTRA_LIBS=
+SR_SEARCH_LIBS([SRD_EXTRA_LIBS], [pow], [m])
 
-SRD_PACKAGE_VERSION_MAJOR=srd_package_version_major
-SRD_PACKAGE_VERSION_MINOR=srd_package_version_minor
-SRD_PACKAGE_VERSION_MICRO=srd_package_version_micro
-SRD_PACKAGE_VERSION=srd_package_version
+AC_SYS_LARGEFILE
 
-AC_SUBST(SRD_PACKAGE_VERSION_MAJOR)
-AC_SUBST(SRD_PACKAGE_VERSION_MINOR)
-AC_SUBST(SRD_PACKAGE_VERSION_MICRO)
-AC_SUBST(SRD_PACKAGE_VERSION)
+##############################
+##  Finalize configuration  ##
+##############################
 
-AM_CONDITIONAL(BUILD_RUNTC, test x"$build_runtc" = "xyes")
+AC_SUBST([SRD_PKGLIBS])
 
-AC_CONFIG_FILES([Makefile version.h libsigrokdecode.pc])
+# Retrieve the compile and link flags for all modules combined.
+# Also, bail out at this point if any module dependency is not met.
+PKG_CHECK_MODULES([LIBSIGROKDECODE], [glib-2.0 >= 2.28.0 $SRD_PKGLIBS])
+PKG_CHECK_MODULES([TESTS], [$SRD_PKGLIBS_TESTS glib-2.0 $SRD_PKGLIBS])
 
-AC_OUTPUT
+srd_glib_version=`$PKG_CONFIG --modversion glib-2.0 2>&AS_MESSAGE_LOG_FD`
 
-echo
-echo "libsigrokdecode configuration summary:"
-echo
-echo "  - Package version (major.minor.micro):    $SRD_PACKAGE_VERSION"
-echo "  - Library version (current:revision:age): $SRD_LIB_VERSION"
-echo "  - Prefix: $prefix"
-echo "  - Building on: $build"
-echo "  - Building for: $host"
-echo
-echo "Detected libraries:"
-echo
-
-if test "x$pyver" = "xnone"; then
-	echo "  - (REQUIRED) python >= 3.2: no"
-else
-	echo "  - (REQUIRED) python >= 3.2: yes ($pyver)"
-fi
-
-# Note: This only works for libs with pkg-config integration.
-for lib in "glib-2.0 >= 2.24.0" "check >= 0.9.4" "libsigrok >= 0.3.0"; do
-	optional="OPTIONAL"
-	if test "x$lib" = "xglib-2.0 >= 2.24.0"; then optional="REQUIRED"; fi
-	if `$PKG_CONFIG --exists $lib`; then
-		ver=`$PKG_CONFIG --modversion $lib`
-		answer="yes ($ver)"
-	else
-		answer="no"
-	fi
-	echo "  - ($optional) $lib: $answer"
-done
-
-echo
-echo "Enabled features:"
-echo
-echo "  - (OPTIONAL) Library unit test framework support: $have_check"
-echo "  - (OPTIONAL) Protocol decoder test framework support: $build_runtc"
-echo
+AC_CONFIG_FILES([Makefile libsigrokdecode.pc])
+
+AC_OUTPUT
 
+cat >&AS_MESSAGE_FD <<_EOF
+
+libsigrokdecode configuration summary:
+ - Package version................. $SRD_PACKAGE_VERSION
+ - Library ABI version............. $SRD_LIB_VERSION
+ - Prefix.......................... $prefix
+ - Building on..................... $build
+ - Building for.................... $host
+
+Compile configuration:
+ - C compiler...................... $CC
+ - C compiler version.............. $srd_cc_version
+ - C compiler flags................ $CFLAGS
+ - Additional C compiler flags..... $SRD_EXTRA_CFLAGS
+ - C compiler warnings............. $SRD_WFLAGS
+
+Detected libraries (required):
+ - glib-2.0 >= 2.28.0.............. $srd_glib_version
+$srd_pkglibs_summary
+Detected libraries (optional):
+$srd_pkglibs_opt_summary
+_EOF
diff --git a/decoder.c b/decoder.c
index 71e9122..1151f05 100644
--- a/decoder.c
+++ b/decoder.c
@@ -18,9 +18,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "config.h"
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <glib.h>
 
 /**
@@ -39,7 +39,7 @@
 
 /** @cond PRIVATE */
 
-/* The list of protocol decoders. */
+/* The list of loaded protocol decoders. */
 static GSList *pd_list = NULL;
 
 /* srd.c */
@@ -64,9 +64,9 @@ static gboolean srd_check_init(void)
 }
 
 /**
- * Returns the list of supported/loaded protocol decoders.
+ * Returns the list of loaded protocol decoders.
  *
- * This is a GSList containing the names of the decoders as strings.
+ * This is a GSList of pointers to struct srd_decoder items.
  *
  * @return List of decoders, NULL if none are supported or loaded.
  *
@@ -100,199 +100,513 @@ SRD_API struct srd_decoder *srd_decoder_get_by_id(const char *id)
 	return NULL;
 }
 
+static void channel_free(void *data)
+{
+	struct srd_channel *ch = data;
+
+	if (!ch)
+		return;
+
+	g_free(ch->desc);
+	g_free(ch->name);
+	g_free(ch->id);
+	g_free(ch);
+}
+
+static void variant_free(void *data)
+{
+	GVariant *var = data;
+
+	if (!var)
+		return;
+
+	g_variant_unref(var);
+}
+
+static void annotation_row_free(void *data)
+{
+	struct srd_decoder_annotation_row *row = data;
+
+	if (!row)
+		return;
+
+	g_slist_free(row->ann_classes);
+	g_free(row->desc);
+	g_free(row->id);
+	g_free(row);
+}
+
+static void decoder_option_free(void *data)
+{
+	struct srd_decoder_option *opt = data;
+
+	if (!opt)
+		return;
+
+	g_slist_free_full(opt->values, &variant_free);
+	variant_free(opt->def);
+	g_free(opt->desc);
+	g_free(opt->id);
+	g_free(opt);
+}
+
+static void decoder_free(struct srd_decoder *dec)
+{
+	if (!dec)
+		return;
+
+	Py_XDECREF(dec->py_dec);
+	Py_XDECREF(dec->py_mod);
+
+	g_slist_free_full(dec->options, &decoder_option_free);
+	g_slist_free_full(dec->binary, (GDestroyNotify)&g_strfreev);
+	g_slist_free_full(dec->annotation_rows, &annotation_row_free);
+	g_slist_free_full(dec->annotations, (GDestroyNotify)&g_strfreev);
+	g_slist_free_full(dec->opt_channels, &channel_free);
+	g_slist_free_full(dec->channels, &channel_free);
+
+	g_free(dec->license);
+	g_free(dec->desc);
+	g_free(dec->longname);
+	g_free(dec->name);
+	g_free(dec->id);
+
+	g_free(dec);
+}
+
 static int get_channels(const struct srd_decoder *d, const char *attr,
-		GSList **pdchl)
+		GSList **out_pdchl, int offset)
 {
 	PyObject *py_channellist, *py_entry;
 	struct srd_channel *pdch;
-	int ret, num_channels, i;
+	GSList *pdchl;
+	ssize_t i;
 
 	if (!PyObject_HasAttrString(d->py_dec, attr))
 		/* No channels of this type specified. */
 		return SRD_OK;
 
+	pdchl = NULL;
+
 	py_channellist = PyObject_GetAttrString(d->py_dec, attr);
+	if (!py_channellist)
+		goto except_out;
+
 	if (!PyTuple_Check(py_channellist)) {
 		srd_err("Protocol decoder %s %s attribute is not a tuple.",
-				d->name, attr);
-		return SRD_ERR_PYTHON;
+			d->name, attr);
+		goto err_out;
 	}
 
-	if ((num_channels = PyTuple_Size(py_channellist)) == 0)
-		/* Empty channellist. */
-		return SRD_OK;
-
-	ret = SRD_OK;
-	for (i = 0; i < num_channels; i++) {
+	for (i = PyTuple_Size(py_channellist) - 1; i >= 0; i--) {
 		py_entry = PyTuple_GetItem(py_channellist, i);
+		if (!py_entry)
+			goto except_out;
+
 		if (!PyDict_Check(py_entry)) {
 			srd_err("Protocol decoder %s %s attribute is not "
-				"a list with dict elements.", d->name, attr);
-			ret = SRD_ERR_PYTHON;
-			break;
-		}
-
-		if (!(pdch = g_try_malloc(sizeof(struct srd_channel)))) {
-			srd_err("Failed to g_malloc() struct srd_channel.");
-			ret = SRD_ERR_MALLOC;
-			break;
+				"a list of dict elements.", d->name, attr);
+			goto err_out;
 		}
+		pdch = g_malloc0(sizeof(struct srd_channel));
+		/* Add to list right away so it doesn't get lost. */
+		pdchl = g_slist_prepend(pdchl, pdch);
 
-		if ((py_dictitem_as_str(py_entry, "id", &pdch->id)) != SRD_OK) {
-			ret = SRD_ERR_PYTHON;
-			break;
-		}
-		if ((py_dictitem_as_str(py_entry, "name", &pdch->name)) != SRD_OK) {
-			ret = SRD_ERR_PYTHON;
-			break;
-		}
-		if ((py_dictitem_as_str(py_entry, "desc", &pdch->desc)) != SRD_OK) {
-			ret = SRD_ERR_PYTHON;
-			break;
-		}
-		pdch->order = i;
+		if (py_dictitem_as_str(py_entry, "id", &pdch->id) != SRD_OK)
+			goto err_out;
+		if (py_dictitem_as_str(py_entry, "name", &pdch->name) != SRD_OK)
+			goto err_out;
+		if (py_dictitem_as_str(py_entry, "desc", &pdch->desc) != SRD_OK)
+			goto err_out;
 
-		*pdchl = g_slist_append(*pdchl, pdch);
+		pdch->order = offset + i;
 	}
 
-	Py_DecRef(py_channellist);
+	Py_DECREF(py_channellist);
+	*out_pdchl = pdchl;
 
-	return ret;
+	return SRD_OK;
+
+except_out:
+	srd_exception_catch("Failed to get %s list of %s decoder",
+			attr, d->name);
+err_out:
+	g_slist_free_full(pdchl, &channel_free);
+	Py_XDECREF(py_channellist);
+
+	return SRD_ERR_PYTHON;
 }
 
 static int get_options(struct srd_decoder *d)
 {
-	PyObject *py_opts, *py_opt, *py_val, *py_default, *py_item;
-	Py_ssize_t opt, i;
+	PyObject *py_opts, *py_opt, *py_str, *py_values, *py_default, *py_item;
+	GSList *options;
 	struct srd_decoder_option *o;
 	GVariant *gvar;
-	gint64 lval;
-	double dval;
-	int overflow;
-	char *sval;
+	ssize_t opt, i;
 
 	if (!PyObject_HasAttrString(d->py_dec, "options"))
 		/* No options, that's fine. */
 		return SRD_OK;
 
+	options = NULL;
+
 	/* If present, options must be a tuple. */
 	py_opts = PyObject_GetAttrString(d->py_dec, "options");
+	if (!py_opts)
+		goto except_out;
+
 	if (!PyTuple_Check(py_opts)) {
 		srd_err("Protocol decoder %s: options attribute is not "
 				"a tuple.", d->id);
-		return SRD_ERR_PYTHON;
+		goto err_out;
 	}
 
-	for (opt = 0; opt < PyTuple_Size(py_opts); opt++) {
+	for (opt = PyTuple_Size(py_opts) - 1; opt >= 0; opt--) {
 		py_opt = PyTuple_GetItem(py_opts, opt);
+		if (!py_opt)
+			goto except_out;
+
 		if (!PyDict_Check(py_opt)) {
 			srd_err("Protocol decoder %s options: each option "
 					"must consist of a dictionary.", d->name);
-			return SRD_ERR_PYTHON;
-		}
-		if (!(py_val = PyDict_GetItemString(py_opt, "id"))) {
-			srd_err("Protocol decoder %s option %d has no "
-					"id.", d->name);
-			return SRD_ERR_PYTHON;
+			goto err_out;
 		}
+
 		o = g_malloc0(sizeof(struct srd_decoder_option));
-		py_str_as_str(py_val, &o->id);
-
-		if ((py_val = PyDict_GetItemString(py_opt, "desc")))
-			py_str_as_str(py_val, &o->desc);
-
-		if ((py_default = PyDict_GetItemString(py_opt, "default"))) {
-			if (PyUnicode_Check(py_default)) {
-				/* UTF-8 string */
-				py_str_as_str(py_default, &sval);
-				o->def = g_variant_new_string(sval);
-				g_free(sval);
-			} else if (PyLong_Check(py_default)) {
-				/* Long */
-				lval = PyLong_AsLongAndOverflow(py_default, &overflow);
-				if (overflow) {
-					/* Value is < LONG_MIN or > LONG_MAX */
-					PyErr_Clear();
-					srd_err("Protocol decoder %s option 'default' has "
-							"invalid default value.", d->name);
-					return SRD_ERR_PYTHON;
-				}
-				o->def = g_variant_new_int64(lval);
-			} else if (PyFloat_Check(py_default)) {
-				/* Float */
-				if ((dval = PyFloat_AsDouble(py_default)) == -1.0) {
-					PyErr_Clear();
-					srd_err("Protocol decoder %s option 'default' has "
-							"invalid default value.", d->name);
-					return SRD_ERR_PYTHON;
-				}
-				o->def = g_variant_new_double(dval);
-			} else {
+		/* Add to list right away so it doesn't get lost. */
+		options = g_slist_prepend(options, o);
+
+		py_str = PyDict_GetItemString(py_opt, "id");
+		if (!py_str) {
+			srd_err("Protocol decoder %s option %zd has no id.",
+				d->name, opt);
+			goto err_out;
+		}
+		if (py_str_as_str(py_str, &o->id) != SRD_OK)
+			goto err_out;
+
+		py_str = PyDict_GetItemString(py_opt, "desc");
+		if (py_str) {
+			if (py_str_as_str(py_str, &o->desc) != SRD_OK)
+				goto err_out;
+		}
+
+		py_default = PyDict_GetItemString(py_opt, "default");
+		if (py_default) {
+			gvar = py_obj_to_variant(py_default);
+			if (!gvar) {
 				srd_err("Protocol decoder %s option 'default' has "
-						"value of unsupported type '%s'.", d->name,
-						Py_TYPE(py_default)->tp_name);
-				return SRD_ERR_PYTHON;
+					"invalid default value.", d->name);
+				goto err_out;
 			}
-			g_variant_ref_sink(o->def);
+			o->def = g_variant_ref_sink(gvar);
 		}
 
-		if ((py_val = PyDict_GetItemString(py_opt, "values"))) {
+		py_values = PyDict_GetItemString(py_opt, "values");
+		if (py_values) {
 			/* A default is required if a list of values is
 			 * given, since it's used to verify their type. */
 			if (!o->def) {
-				srd_err("No default for option '%s'", o->id);
-				return SRD_ERR_PYTHON;
+				srd_err("No default for option '%s'.", o->id);
+				goto err_out;
 			}
-			if (!PyTuple_Check(py_val)) {
+			if (!PyTuple_Check(py_values)) {
 				srd_err("Option '%s' values should be a tuple.", o->id);
-				return SRD_ERR_PYTHON;
+				goto err_out;
 			}
-			for (i = 0; i < PyTuple_Size(py_val); i++) {
-				py_item = PyTuple_GetItem(py_val, i);
+
+			for (i = PyTuple_Size(py_values) - 1; i >= 0; i--) {
+				py_item = PyTuple_GetItem(py_values, i);
+				if (!py_item)
+					goto except_out;
+
 				if (Py_TYPE(py_default) != Py_TYPE(py_item)) {
 					srd_err("All values for option '%s' must be "
-							"of the same type as the default.",
-							o->id);
-					return SRD_ERR_PYTHON;
+						"of the same type as the default.",
+						o->id);
+					goto err_out;
 				}
-				if (PyUnicode_Check(py_item)) {
-					/* UTF-8 string */
-					py_str_as_str(py_item, &sval);
-					gvar = g_variant_new_string(sval);
-					g_variant_ref_sink(gvar);
-					g_free(sval);
-					o->values = g_slist_append(o->values, gvar);
-				} else if (PyLong_Check(py_item)) {
-					/* Long */
-					lval = PyLong_AsLongAndOverflow(py_item, &overflow);
-					if (overflow) {
-						/* Value is < LONG_MIN or > LONG_MAX */
-						PyErr_Clear();
-						srd_err("Protocol decoder %s option 'values' "
-								"has invalid value.", d->name);
-						return SRD_ERR_PYTHON;
-					}
-					gvar = g_variant_new_int64(lval);
-					g_variant_ref_sink(gvar);
-					o->values = g_slist_append(o->values, gvar);
-				} else if (PyFloat_Check(py_item)) {
-					/* Float */
-					if ((dval = PyFloat_AsDouble(py_item)) == -1.0) {
-						PyErr_Clear();
-						srd_err("Protocol decoder %s option 'default' has "
-								"invalid default value.", d->name);
-						return SRD_ERR_PYTHON;
-					}
-					gvar = g_variant_new_double(dval);
-					g_variant_ref_sink(gvar);
-					o->values = g_slist_append(o->values, gvar);
+				gvar = py_obj_to_variant(py_item);
+				if (!gvar) {
+					srd_err("Protocol decoder %s option 'values' "
+						"contains invalid value.", d->name);
+					goto err_out;
 				}
+				o->values = g_slist_prepend(o->values,
+						g_variant_ref_sink(gvar));
 			}
 		}
-		d->options = g_slist_append(d->options, o);
 	}
+	d->options = options;
+	Py_DECREF(py_opts);
+
+	return SRD_OK;
+
+except_out:
+	srd_exception_catch("Failed to get %s decoder options", d->name);
+err_out:
+	g_slist_free_full(options, &decoder_option_free);
+	Py_XDECREF(py_opts);
+
+	return SRD_ERR_PYTHON;
+}
+
+/* Convert annotation class attribute to GSList of char **.
+ */
+static int get_annotations(struct srd_decoder *dec)
+{
+	PyObject *py_annlist, *py_ann;
+	GSList *annotations;
+	char **annpair;
+	ssize_t i;
+
+	if (!PyObject_HasAttrString(dec->py_dec, "annotations"))
+		return SRD_OK;
+
+	annotations = NULL;
+
+	py_annlist = PyObject_GetAttrString(dec->py_dec, "annotations");
+	if (!py_annlist)
+		goto except_out;
+
+	if (!PyTuple_Check(py_annlist)) {
+		srd_err("Protocol decoder %s annotations should "
+			"be a tuple.", dec->name);
+		goto err_out;
+	}
+
+	for (i = PyTuple_Size(py_annlist) - 1; i >= 0; i--) {
+		py_ann = PyTuple_GetItem(py_annlist, i);
+		if (!py_ann)
+			goto except_out;
+
+		if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
+			srd_err("Protocol decoder %s annotation %zd should "
+				"be a tuple with two elements.",
+				dec->name, i + 1);
+			goto err_out;
+		}
+		if (py_strseq_to_char(py_ann, &annpair) != SRD_OK)
+			goto err_out;
+
+		annotations = g_slist_prepend(annotations, annpair);
+	}
+	dec->annotations = annotations;
+	Py_DECREF(py_annlist);
 
 	return SRD_OK;
+
+except_out:
+	srd_exception_catch("Failed to get %s decoder annotations", dec->name);
+err_out:
+	g_slist_free_full(annotations, (GDestroyNotify)&g_strfreev);
+	Py_XDECREF(py_annlist);
+
+	return SRD_ERR_PYTHON;
+}
+
+/* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'.
+ */
+static int get_annotation_rows(struct srd_decoder *dec)
+{
+	PyObject *py_ann_rows, *py_ann_row, *py_ann_classes, *py_item;
+	GSList *annotation_rows;
+	struct srd_decoder_annotation_row *ann_row;
+	ssize_t i, k;
+	size_t class_idx;
+
+	if (!PyObject_HasAttrString(dec->py_dec, "annotation_rows"))
+		return SRD_OK;
+
+	annotation_rows = NULL;
+
+	py_ann_rows = PyObject_GetAttrString(dec->py_dec, "annotation_rows");
+	if (!py_ann_rows)
+		goto except_out;
+
+	if (!PyTuple_Check(py_ann_rows)) {
+		srd_err("Protocol decoder %s annotation_rows "
+			"must be a tuple.", dec->name);
+		goto err_out;
+	}
+
+	for (i = PyTuple_Size(py_ann_rows) - 1; i >= 0; i--) {
+		py_ann_row = PyTuple_GetItem(py_ann_rows, i);
+		if (!py_ann_row)
+			goto except_out;
+
+		if (!PyTuple_Check(py_ann_row) || PyTuple_Size(py_ann_row) != 3) {
+			srd_err("Protocol decoder %s annotation_rows "
+				"must contain only tuples of 3 elements.",
+				dec->name);
+			goto err_out;
+		}
+		ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
+		/* Add to list right away so it doesn't get lost. */
+		annotation_rows = g_slist_prepend(annotation_rows, ann_row);
+
+		py_item = PyTuple_GetItem(py_ann_row, 0);
+		if (!py_item)
+			goto except_out;
+		if (py_str_as_str(py_item, &ann_row->id) != SRD_OK)
+			goto err_out;
+
+		py_item = PyTuple_GetItem(py_ann_row, 1);
+		if (!py_item)
+			goto except_out;
+		if (py_str_as_str(py_item, &ann_row->desc) != SRD_OK)
+			goto err_out;
+
+		py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
+		if (!py_ann_classes)
+			goto except_out;
+
+		if (!PyTuple_Check(py_ann_classes)) {
+			srd_err("Protocol decoder %s annotation_rows tuples "
+				"must have a tuple of numbers as 3rd element.",
+				dec->name);
+			goto err_out;
+		}
+
+		for (k = PyTuple_Size(py_ann_classes) - 1; k >= 0; k--) {
+			py_item = PyTuple_GetItem(py_ann_classes, k);
+			if (!py_item)
+				goto except_out;
+
+			if (!PyLong_Check(py_item)) {
+				srd_err("Protocol decoder %s annotation row "
+					"class tuple must only contain numbers.",
+					dec->name);
+				goto err_out;
+			}
+			class_idx = PyLong_AsSize_t(py_item);
+			if (PyErr_Occurred())
+				goto except_out;
+
+			ann_row->ann_classes = g_slist_prepend(ann_row->ann_classes,
+					GSIZE_TO_POINTER(class_idx));
+		}
+	}
+	dec->annotation_rows = annotation_rows;
+	Py_DECREF(py_ann_rows);
+
+	return SRD_OK;
+
+except_out:
+	srd_exception_catch("Failed to get %s decoder annotation rows",
+			dec->name);
+err_out:
+	g_slist_free_full(annotation_rows, &annotation_row_free);
+	Py_XDECREF(py_ann_rows);
+
+	return SRD_ERR_PYTHON;
+}
+
+/* Convert binary classes to GSList of char **.
+ */
+static int get_binary_classes(struct srd_decoder *dec)
+{
+	PyObject *py_bin_classes, *py_bin_class;
+	GSList *bin_classes;
+	char **bin;
+	ssize_t i;
+
+	if (!PyObject_HasAttrString(dec->py_dec, "binary"))
+		return SRD_OK;
+
+	bin_classes = NULL;
+
+	py_bin_classes = PyObject_GetAttrString(dec->py_dec, "binary");
+	if (!py_bin_classes)
+		goto except_out;
+
+	if (!PyTuple_Check(py_bin_classes)) {
+		srd_err("Protocol decoder %s binary classes should "
+			"be a tuple.", dec->name);
+		goto err_out;
+	}
+
+	for (i = PyTuple_Size(py_bin_classes) - 1; i >= 0; i--) {
+		py_bin_class = PyTuple_GetItem(py_bin_classes, i);
+		if (!py_bin_class)
+			goto except_out;
+
+		if (!PyTuple_Check(py_bin_class)
+				|| PyTuple_Size(py_bin_class) != 2) {
+			srd_err("Protocol decoder %s binary classes should "
+				"consist only of tuples of 2 elements.",
+				dec->name);
+			goto err_out;
+		}
+		if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK)
+			goto err_out;
+
+		bin_classes = g_slist_prepend(bin_classes, bin);
+	}
+	dec->binary = bin_classes;
+	Py_DECREF(py_bin_classes);
+
+	return SRD_OK;
+
+except_out:
+	srd_exception_catch("Failed to get %s decoder binary classes",
+			dec->name);
+err_out:
+	g_slist_free_full(bin_classes, (GDestroyNotify)&g_strfreev);
+	Py_XDECREF(py_bin_classes);
+
+	return SRD_ERR_PYTHON;
+}
+
+/* Check whether the Decoder class defines the named method.
+ */
+static int check_method(PyObject *py_dec, const char *mod_name,
+		const char *method_name)
+{
+	PyObject *py_method;
+	int is_callable;
+
+	py_method = PyObject_GetAttrString(py_dec, method_name);
+	if (!py_method) {
+		srd_exception_catch("Protocol decoder %s Decoder class "
+				"has no %s() method", mod_name, method_name);
+		return SRD_ERR_PYTHON;
+	}
+
+	is_callable = PyCallable_Check(py_method);
+	Py_DECREF(py_method);
+
+	if (!is_callable) {
+		srd_err("Protocol decoder %s Decoder class attribute '%s' "
+			"is not a method.", mod_name, method_name);
+		return SRD_ERR_PYTHON;
+	}
+
+	return SRD_OK;
+}
+
+/**
+ * Get the API version of the specified decoder.
+ *
+ * @param d The decoder to use. Must not be NULL.
+ *
+ * @return The API version of the decoder, or 0 upon errors.
+ */
+SRD_PRIV long srd_decoder_apiver(const struct srd_decoder *d)
+{
+	PyObject *py_apiver;
+	long apiver;
+
+	if (!d)
+		return 0;
+
+	py_apiver = PyObject_GetAttrString(d->py_dec, "api_version");
+	apiver = (py_apiver && PyLong_Check(py_apiver))
+			? PyLong_AsLong(py_apiver) : 0;
+	Py_XDECREF(py_apiver);
+
+	return apiver;
 }
 
 /**
@@ -306,15 +620,11 @@ static int get_options(struct srd_decoder *d)
  */
 SRD_API int srd_decoder_load(const char *module_name)
 {
-	PyObject *py_basedec, *py_method, *py_attr, *py_annlist, *py_ann;
-	PyObject *py_bin_classes, *py_bin_class, *py_ann_rows, *py_ann_row;
-	PyObject *py_ann_classes, *py_long;
+	PyObject *py_basedec;
 	struct srd_decoder *d;
-	int ret, i, j;
-	char **ann, **bin, *ann_row_id, *ann_row_desc;
-	struct srd_channel *pdch;
-	GSList *l, *ann_classes;
-	struct srd_decoder_annotation_row *ann_row;
+	long apiver;
+	int is_subclass;
+	const char *fail_txt;
 
 	if (!srd_check_init())
 		return SRD_ERR;
@@ -329,246 +639,147 @@ SRD_API int srd_decoder_load(const char *module_name)
 
 	srd_dbg("Loading protocol decoder '%s'.", module_name);
 
-	py_basedec = py_method = py_attr = NULL;
+	d = g_malloc0(sizeof(struct srd_decoder));
+	fail_txt = NULL;
 
-	if (!(d = g_try_malloc0(sizeof(struct srd_decoder)))) {
-		srd_dbg("Failed to g_malloc() struct srd_decoder.");
-		ret = SRD_ERR_MALLOC;
-		goto err_out;
+	d->py_mod = py_import_by_name(module_name);
+	if (!d->py_mod) {
+		fail_txt = "import by name failed";
+		goto except_out;
 	}
 
-	ret = SRD_ERR_PYTHON;
-
-	/* Import the Python module. */
-	if (!(d->py_mod = PyImport_ImportModule(module_name))) {
-		srd_exception_catch("Import of '%s' failed.", module_name);
+	if (!mod_sigrokdecode) {
+		srd_err("sigrokdecode module not loaded.");
+		fail_txt = "sigrokdecode(3) not loaded";
 		goto err_out;
 	}
 
 	/* Get the 'Decoder' class as Python object. */
-	if (!(d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"))) {
-		/* This generated an AttributeError exception. */
-		PyErr_Clear();
-		srd_err("Decoder class not found in protocol decoder %s.",
-			module_name);
-		goto err_out;
+	d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder");
+	if (!d->py_dec) {
+		fail_txt = "no 'Decoder' attribute in imported module";
+		goto except_out;
 	}
 
-	if (!(py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"))) {
-		srd_dbg("sigrokdecode module not loaded.");
-		goto err_out;
+	py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder");
+	if (!py_basedec) {
+		fail_txt = "no 'Decoder' attribute in sigrokdecode(3)";
+		goto except_out;
 	}
 
-	if (!PyObject_IsSubclass(d->py_dec, py_basedec)) {
+	is_subclass = PyObject_IsSubclass(d->py_dec, py_basedec);
+	Py_DECREF(py_basedec);
+
+	if (!is_subclass) {
 		srd_err("Decoder class in protocol decoder module %s is not "
 			"a subclass of sigrokdecode.Decoder.", module_name);
+		fail_txt = "not a subclass of sigrokdecode.Decoder";
 		goto err_out;
 	}
-	Py_CLEAR(py_basedec);
 
 	/*
-	 * Check that thіs decoder has the correct PD API version.
+	 * Check that this decoder has the correct PD API version.
 	 * PDs of different API versions are incompatible and cannot work.
 	 */
-	py_long = PyObject_GetAttrString(d->py_dec, "api_version");
-	if (PyLong_AsLong(py_long) != 2) {
-		srd_err("Only PDs of API version 2 are supported.");
+	apiver = srd_decoder_apiver(d);
+	if (apiver != 2) {
+		srd_exception_catch("Only PD API version 2 is supported, "
+			"decoder %s has version %ld", module_name, apiver);
+		fail_txt = "API version mismatch";
 		goto err_out;
 	}
-	Py_CLEAR(py_long);
 
-	/* Check for a proper start() method. */
-	if (!PyObject_HasAttrString(d->py_dec, "start")) {
-		srd_err("Protocol decoder %s has no start() method Decoder "
-			"class.", module_name);
-		goto err_out;
-	}
-	py_method = PyObject_GetAttrString(d->py_dec, "start");
-	if (!PyFunction_Check(py_method)) {
-		srd_err("Protocol decoder %s Decoder class attribute 'start' "
-			"is not a method.", module_name);
+	/* Check Decoder class for required methods.
+	 */
+	if (check_method(d->py_dec, module_name, "start") != SRD_OK) {
+		fail_txt = "no 'start()' method";
 		goto err_out;
 	}
-	Py_CLEAR(py_method);
 
-	/* Check for a proper decode() method. */
-	if (!PyObject_HasAttrString(d->py_dec, "decode")) {
-		srd_err("Protocol decoder %s has no decode() method Decoder "
-			"class.", module_name);
-		goto err_out;
-	}
-	py_method = PyObject_GetAttrString(d->py_dec, "decode");
-	if (!PyFunction_Check(py_method)) {
-		srd_err("Protocol decoder %s Decoder class attribute 'decode' "
-			"is not a method.", module_name);
+	if (check_method(d->py_dec, module_name, "decode") != SRD_OK) {
+		fail_txt = "no 'decode()' method";
 		goto err_out;
 	}
-	Py_CLEAR(py_method);
 
 	/* Store required fields in newly allocated strings. */
-	if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK)
+	if (py_attr_as_str(d->py_dec, "id", &(d->id)) != SRD_OK) {
+		fail_txt = "no 'id' attribute";
 		goto err_out;
+	}
 
-	if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK)
+	if (py_attr_as_str(d->py_dec, "name", &(d->name)) != SRD_OK) {
+		fail_txt = "no 'name' attribute";
 		goto err_out;
+	}
 
-	if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK)
+	if (py_attr_as_str(d->py_dec, "longname", &(d->longname)) != SRD_OK) {
+		fail_txt = "no 'longname' attribute";
 		goto err_out;
+	}
 
-	if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK)
+	if (py_attr_as_str(d->py_dec, "desc", &(d->desc)) != SRD_OK) {
+		fail_txt = "no 'desc' attribute";
 		goto err_out;
+	}
 
-	if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK)
+	if (py_attr_as_str(d->py_dec, "license", &(d->license)) != SRD_OK) {
+		fail_txt = "no 'license' attribute";
 		goto err_out;
+	}
 
 	/* All options and their default values. */
-	if (get_options(d) != SRD_OK)
+	if (get_options(d) != SRD_OK) {
+		fail_txt = "cannot get options";
 		goto err_out;
+	}
 
 	/* Check and import required channels. */
-	if (get_channels(d, "channels", &d->channels) != SRD_OK)
+	if (get_channels(d, "channels", &d->channels, 0) != SRD_OK) {
+		fail_txt = "cannot get channels";
 		goto err_out;
+	}
 
 	/* Check and import optional channels. */
-	if (get_channels(d, "optional_channels", &d->opt_channels) != SRD_OK)
+	if (get_channels(d, "optional_channels", &d->opt_channels,
+				g_slist_length(d->channels)) != SRD_OK) {
+		fail_txt = "cannot get optional channels";
 		goto err_out;
-
-	/*
-	 * Fix order numbers for the optional channels.
-	 *
-	 * Example:
-	 * Required channels: r1, r2, r3. Optional: o1, o2, o3, o4.
-	 * 'order' fields in the d->channels list = 0, 1, 2.
-	 * 'order' fields in the d->opt_channels list = 3, 4, 5, 6.
-	 */
-	for (l = d->opt_channels; l; l = l->next) {
-		pdch = l->data;
-		pdch->order += g_slist_length(d->channels);
-	}
-
-	/* Convert annotation class attribute to GSList of char **. */
-	d->annotations = NULL;
-	if (PyObject_HasAttrString(d->py_dec, "annotations")) {
-		py_annlist = PyObject_GetAttrString(d->py_dec, "annotations");
-		if (!PyTuple_Check(py_annlist)) {
-			srd_err("Protocol decoder %s annotations should "
-					"be a tuple.", module_name);
-			goto err_out;
-		}
-		for (i = 0; i < PyTuple_Size(py_annlist); i++) {
-			py_ann = PyTuple_GetItem(py_annlist, i);
-			if (!PyTuple_Check(py_ann) || PyTuple_Size(py_ann) != 2) {
-				srd_err("Protocol decoder %s annotation %d should "
-						"be a tuple with two elements.", module_name, i + 1);
-				goto err_out;
-			}
-
-			if (py_strseq_to_char(py_ann, &ann) != SRD_OK) {
-				goto err_out;
-			}
-			d->annotations = g_slist_append(d->annotations, ann);
-		}
 	}
 
-	/* Convert annotation_rows to GSList of 'struct srd_decoder_annotation_row'. */
-	d->annotation_rows = NULL;
-	if (PyObject_HasAttrString(d->py_dec, "annotation_rows")) {
-		py_ann_rows = PyObject_GetAttrString(d->py_dec, "annotation_rows");
-		if (!PyTuple_Check(py_ann_rows)) {
-			srd_err("Protocol decoder %s annotation row list "
-				"must be a tuple.", module_name);
-			goto err_out;
-		}
-		for (i = 0; i < PyTuple_Size(py_ann_rows); i++) {
-			py_ann_row = PyTuple_GetItem(py_ann_rows, i);
-			if (!PyTuple_Check(py_ann_row)) {
-				srd_err("Protocol decoder %s annotation rows "
-					"must be tuples.", module_name);
-				goto err_out;
-			}
-			if (PyTuple_Size(py_ann_row) != 3
-					|| !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 0))
-					|| !PyUnicode_Check(PyTuple_GetItem(py_ann_row, 1))
-					|| !PyTuple_Check(PyTuple_GetItem(py_ann_row, 2))) {
-				srd_err("Protocol decoder %s annotation rows "
-					"must contain tuples containing two "
-					"strings and a tuple.", module_name);
-				goto err_out;
-			}
-
-			if (py_str_as_str(PyTuple_GetItem(py_ann_row, 0), &ann_row_id) != SRD_OK)
-				goto err_out;
-
-			if (py_str_as_str(PyTuple_GetItem(py_ann_row, 1), &ann_row_desc) != SRD_OK)
-				goto err_out;
-
-			py_ann_classes = PyTuple_GetItem(py_ann_row, 2);
-			ann_classes = NULL;
-			for (j = 0; j < PyTuple_Size(py_ann_classes); j++) {
-				py_long = PyTuple_GetItem(py_ann_classes, j);
-				if (!PyLong_Check(py_long)) {
-					srd_err("Protocol decoder %s annotation row class "
-						"list must only contain numbers.", module_name);
-					goto err_out;
-				}
-				ann_classes = g_slist_append(ann_classes,
-					GINT_TO_POINTER(PyLong_AsLong(py_long)));
-			}
-
-			ann_row = g_malloc0(sizeof(struct srd_decoder_annotation_row));
-			ann_row->id = ann_row_id;
-			ann_row->desc = ann_row_desc;
-			ann_row->ann_classes = ann_classes;
-			d->annotation_rows = g_slist_append(d->annotation_rows, ann_row);
-		}
+	if (get_annotations(d) != SRD_OK) {
+		fail_txt = "cannot get annotations";
+		goto err_out;
 	}
 
-	/* Convert binary class to GSList of char *. */
-	d->binary = NULL;
-	if (PyObject_HasAttrString(d->py_dec, "binary")) {
-		py_bin_classes = PyObject_GetAttrString(d->py_dec, "binary");
-		if (!PyTuple_Check(py_bin_classes)) {
-			srd_err("Protocol decoder %s binary classes should "
-					"be a tuple.", module_name);
-			goto err_out;
-		}
-		for (i = 0; i < PyTuple_Size(py_bin_classes); i++) {
-			py_bin_class = PyTuple_GetItem(py_bin_classes, i);
-			if (!PyTuple_Check(py_bin_class)) {
-				srd_err("Protocol decoder %s binary classes "
-						"should consist of tuples.", module_name);
-				goto err_out;
-			}
-			if (PyTuple_Size(py_bin_class) != 2
-					|| !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 0))
-					|| !PyUnicode_Check(PyTuple_GetItem(py_bin_class, 1))) {
-				srd_err("Protocol decoder %s binary classes should "
-						"contain tuples with two strings.", module_name);
-				goto err_out;
-			}
+	if (get_annotation_rows(d) != SRD_OK) {
+		fail_txt = "cannot get annotation rows";
+		goto err_out;
+	}
 
-			if (py_strseq_to_char(py_bin_class, &bin) != SRD_OK) {
-				goto err_out;
-			}
-			d->binary = g_slist_append(d->binary, bin);
-		}
+	if (get_binary_classes(d) != SRD_OK) {
+		fail_txt = "cannot get binary classes";
+		goto err_out;
 	}
 
-	/* Append it to the list of supported/loaded decoders. */
+	/* Append it to the list of loaded decoders. */
 	pd_list = g_slist_append(pd_list, d);
 
-	ret = SRD_OK;
+	return SRD_OK;
 
-err_out:
-	if (ret != SRD_OK) {
-		Py_XDECREF(py_method);
-		Py_XDECREF(py_basedec);
-		Py_XDECREF(d->py_dec);
-		Py_XDECREF(d->py_mod);
-		g_free(d);
+except_out:
+	if (fail_txt) {
+		srd_exception_catch("Failed to load decoder %s: %s",
+				    module_name, fail_txt);
+		fail_txt = NULL;
+	} else {
+		srd_exception_catch("Failed to load decoder %s", module_name);
 	}
+err_out:
+	if (fail_txt)
+		srd_err("Failed to load decoder %s: %s", module_name, fail_txt);
+	decoder_free(d);
 
-	return ret;
+	return SRD_ERR_PYTHON;
 }
 
 /**
@@ -596,36 +807,18 @@ SRD_API char *srd_decoder_doc_get(const struct srd_decoder *dec)
 		return NULL;
 
 	if (!(py_str = PyObject_GetAttrString(dec->py_mod, "__doc__"))) {
-		srd_exception_catch("");
+		srd_exception_catch("Failed to get docstring");
 		return NULL;
 	}
 
 	doc = NULL;
 	if (py_str != Py_None)
 		py_str_as_str(py_str, &doc);
-	Py_DecRef(py_str);
+	Py_DECREF(py_str);
 
 	return doc;
 }
 
-static void free_channels(GSList *channellist)
-{
-	GSList *l;
-	struct srd_channel *pdch;
-
-	if (channellist == NULL)
-		return;
-
-	for (l = channellist; l; l = l->next) {
-		pdch = l->data;
-		g_free(pdch->id);
-		g_free(pdch->name);
-		g_free(pdch->desc);
-		g_free(pdch);
-	}
-	g_slist_free(channellist);
-}
-
 /**
  * Unload the specified protocol decoder.
  *
@@ -637,7 +830,6 @@ static void free_channels(GSList *channellist)
  */
 SRD_API int srd_decoder_unload(struct srd_decoder *dec)
 {
-	struct srd_decoder_option *o;
 	struct srd_session *sess;
 	GSList *l;
 
@@ -660,31 +852,92 @@ SRD_API int srd_decoder_unload(struct srd_decoder *dec)
 		srd_inst_free_all(sess, NULL);
 	}
 
-	for (l = dec->options; l; l = l->next) {
-		o = l->data;
-		g_free(o->id);
-		g_free(o->desc);
-		g_variant_unref(o->def);
-		g_free(o);
-	}
-	g_slist_free(dec->options);
+	/* Remove the PD from the list of loaded decoders. */
+	pd_list = g_slist_remove(pd_list, dec);
 
-	free_channels(dec->channels);
-	free_channels(dec->opt_channels);
-	g_free(dec->id);
-	g_free(dec->name);
-	g_free(dec->longname);
-	g_free(dec->desc);
-	g_free(dec->license);
+	decoder_free(dec);
 
-	/* The module's Decoder class. */
-	Py_XDECREF(dec->py_dec);
-	/* The module itself. */
-	Py_XDECREF(dec->py_mod);
+	return SRD_OK;
+}
 
-	g_free(dec);
+static void srd_decoder_load_all_zip_path(char *path)
+{
+	PyObject *zipimport_mod, *zipimporter_class, *zipimporter;
+	PyObject *prefix_obj, *files, *key, *value, *set, *modname;
+	Py_ssize_t pos = 0;
+	char *prefix;
+	size_t prefix_len;
 
-	return SRD_OK;
+	set = files = prefix_obj = zipimporter = zipimporter_class = NULL;
+
+	zipimport_mod = py_import_by_name("zipimport");
+	if (zipimport_mod == NULL)
+		goto err_out;
+
+	zipimporter_class = PyObject_GetAttrString(zipimport_mod, "zipimporter");
+	if (zipimporter_class == NULL)
+		goto err_out;
+
+	zipimporter = PyObject_CallFunction(zipimporter_class, "s", path);
+	if (zipimporter == NULL)
+		goto err_out;
+
+	prefix_obj = PyObject_GetAttrString(zipimporter, "prefix");
+	if (prefix_obj == NULL)
+		goto err_out;
+
+	files = PyObject_GetAttrString(zipimporter, "_files");
+	if (files == NULL || !PyDict_Check(files))
+		goto err_out;
+
+	set = PySet_New(NULL);
+	if (set == NULL)
+		goto err_out;
+
+	if (py_str_as_str(prefix_obj, &prefix) != SRD_OK)
+		goto err_out;
+
+	prefix_len = strlen(prefix);
+
+	while (PyDict_Next(files, &pos, &key, &value)) {
+		char *path, *slash;
+		if (py_str_as_str(key, &path) == SRD_OK) {
+			if (strlen(path) > prefix_len
+					&& memcmp(path, prefix, prefix_len) == 0
+					&& (slash = strchr(path + prefix_len, '/'))) {
+
+				modname = PyUnicode_FromStringAndSize(path + prefix_len,
+							slash - (path + prefix_len));
+				if (modname == NULL) {
+					PyErr_Clear();
+				} else {
+					PySet_Add(set, modname);
+					Py_DECREF(modname);
+				}
+			}
+			g_free(path);
+		}
+	}
+	g_free(prefix);
+
+	while ((modname = PySet_Pop(set))) {
+		char *modname_str;
+		if (py_str_as_str(modname, &modname_str) == SRD_OK) {
+			/* The directory name is the module name (e.g. "i2c"). */
+			srd_decoder_load(modname_str);
+			g_free(modname_str);
+		}
+		Py_DECREF(modname);
+	}
+
+err_out:
+	Py_XDECREF(set);
+	Py_XDECREF(files);
+	Py_XDECREF(prefix_obj);
+	Py_XDECREF(zipimporter);
+	Py_XDECREF(zipimporter_class);
+	Py_XDECREF(zipimport_mod);
+	PyErr_Clear();
 }
 
 static void srd_decoder_load_all_path(char *path)
@@ -692,9 +945,12 @@ static void srd_decoder_load_all_path(char *path)
 	GDir *dir;
 	const gchar *direntry;
 
-	if (!(dir = g_dir_open(path, 0, NULL)))
+	if (!(dir = g_dir_open(path, 0, NULL))) {
 		/* Not really fatal */
+		/* Try zipimport method too */
+		srd_decoder_load_all_zip_path(path);
 		return;
+	}
 
 	/* This ignores errors returned by srd_decoder_load(). That
 	 * function will have logged the cause, but in any case we
@@ -736,13 +992,7 @@ SRD_API int srd_decoder_load_all(void)
  */
 SRD_API int srd_decoder_unload_all(void)
 {
-	GSList *l;
-	struct srd_decoder *dec;
-
-	for (l = pd_list; l; l = l->next) {
-		dec = l->data;
-		srd_decoder_unload(dec);
-	}
+	g_slist_foreach(pd_list, (GFunc)srd_decoder_unload, NULL);
 	g_slist_free(pd_list);
 	pd_list = NULL;
 
diff --git a/decoders/ir_nec/__init__.py b/decoders/adns5020/__init__.py
similarity index 78%
copy from decoders/ir_nec/__init__.py
copy to decoders/adns5020/__init__.py
index 84bf428..a0cc63c 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/adns5020/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Karl Palsson <karlp at tweak.net.au>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'spi' PD and decodes ADNS-5020 optical mouse
+sensor commands and data. Use MOSI for the SDIO shared line.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/adns5020/pd.py b/decoders/adns5020/pd.py
new file mode 100644
index 0000000..972227e
--- /dev/null
+++ b/decoders/adns5020/pd.py
@@ -0,0 +1,113 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Karl Palsson <karlp at tweak.net.au>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+regs = {
+	0: 'Product_ID',
+	1: 'Revision_ID',
+	2: 'Motion',
+	3: 'Delta_X',
+	4: 'Delta_Y',
+	5: 'SQUAL',
+	6: 'Shutter_Upper',
+	7: 'Shutter_Lower',
+	8: 'Maximum_Pixel',
+	9: 'Pixel_Sum',
+	0xa: 'Minimum_Pixel',
+	0xb: 'Pixel_Grab',
+	0xd: 'Mouse_Control',
+	0x3a: 'Chip_Reset',
+	0x3f: 'Inv_Rev_ID',
+	0x63: 'Motion_Burst',
+}
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'adns5020'
+    name = 'ADNS-5020'
+    longname = 'Avago ADNS-5020 optical mouse sensor'
+    desc = 'Bidirectional command and data over an SPI-like protocol.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['adns5020']
+    annotations = (
+        ('read', 'Register read commands'),
+        ('write', 'Register write commands'),
+        ('warning', 'Warnings'),
+    )
+    annotation_rows = (
+        ('read', 'Read', (0,)),
+        ('write', 'Write', (1,)),
+        ('warnings', 'Warnings', (2,)),
+    )
+
+    def __init__(self):
+        self.ss_cmd, self.es_cmd = 0, 0
+        self.mosi_bytes = []
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putx(self, data):
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
+
+    def put_warn(self, pos, msg):
+        self.put(pos[0], pos[1], self.out_ann, [2, [msg]])
+
+    def decode(self, ss, es, data):
+        ptype = data[0]
+        if ptype == 'CS-CHANGE':
+            # If we transition high mid-stream, toss out our data and restart.
+            cs_old, cs_new = data[1:]
+            if cs_old is not None and cs_old == 0 and cs_new == 1:
+                if len(self.mosi_bytes) not in [0, 2]:
+                    self.put_warn([self.ss_cmd, es], 'Misplaced CS#!')
+                    self.mosi_bytes = []
+            return
+
+        # Don't care about anything else.
+        if ptype != 'DATA':
+            return
+        mosi, miso = data[1:]
+
+        self.ss, self.es = ss, es
+
+        if len(self.mosi_bytes) == 0:
+            self.ss_cmd = ss
+        self.mosi_bytes.append(mosi)
+
+        # Writes/reads are mostly two transfers (burst mode is different).
+        if len(self.mosi_bytes) != 2:
+            return
+
+        self.es_cmd = es
+        cmd, arg = self.mosi_bytes
+        write = cmd & 0x80
+        reg = cmd & 0x7f
+        reg_desc = regs.get(reg, 'Reserved %#x' % reg)
+        if reg > 0x63:
+            reg_desc = 'Unknown'
+        if write:
+            self.putx([1, ['%s: %#x' % (reg_desc, arg)]])
+        else:
+            self.putx([0, ['%s: %d' % (reg_desc, arg)]])
+
+        self.mosi_bytes = []
diff --git a/decoders/dcf77/__init__.py b/decoders/am230x/__init__.py
similarity index 55%
copy from decoders/dcf77/__init__.py
copy to decoders/am230x/__init__.py
index 04805c2..51b8488 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/am230x/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Johannes Roemer <jroemer at physik.uni-wuerzburg.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
@@ -19,12 +19,19 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This decoder handles the proprietary single wire communication protocol used
+by the Aosong AM230x/DHTxx/RHTxx series of digital humidity and temperature
+sensors.
 
-Details:
-http://en.wikipedia.org/wiki/DCF77
-'''
+Sample rate:
+A sample rate of at least 200kHz is recommended to properly detect all the
+elements of the protocol.
 
-from .pd import *
+Options:
+The AM230x and DHTxx/RHTxx digital humidity and temperature sensors use the
+same single-wire protocol with different encoding of the measured values.
+Therefore the option 'device' must be used to properly decode the
+communication of the respective sensor.
+'''
 
+from .pd import Decoder
diff --git a/decoders/am230x/pd.py b/decoders/am230x/pd.py
new file mode 100644
index 0000000..483dc9b
--- /dev/null
+++ b/decoders/am230x/pd.py
@@ -0,0 +1,235 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Johannes Roemer <jroemer at physik.uni-wuerzburg.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+# Define valid timing values (in microseconds).
+timing = {
+    'START LOW'     : {'min': 750, 'max': 25000},
+    'START HIGH'    : {'min': 10, 'max': 10000},
+    'RESPONSE LOW'  : {'min': 50, 'max': 90},
+    'RESPONSE HIGH' : {'min': 50, 'max': 90},
+    'BIT LOW'       : {'min': 45, 'max': 90},
+    'BIT 0 HIGH'    : {'min': 20, 'max': 35},
+    'BIT 1 HIGH'    : {'min': 65, 'max': 80},
+}
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'am230x'
+    name = 'AM230x/DHTxx/RHTxx'
+    longname = 'Aosong AM230x/DHTxx/RHTxx'
+    desc = 'Aosong AM230x/DHTxx/RHTxx humidity/temperature sensor protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['am230x']
+    channels = (
+        {'id': 'sda', 'name': 'SDA', 'desc': 'Single wire serial data line'},
+    )
+    options = (
+        {'id': 'device', 'desc': 'Device type',
+            'default': 'am230x', 'values': ('am230x/rht', 'dht11')},
+    )
+    annotations = (
+        ('start', 'Start'),
+        ('response', 'Response'),
+        ('bit', 'Bit'),
+        ('end', 'End'),
+        ('byte', 'Byte'),
+        ('humidity', 'Relative humidity in percent'),
+        ('temperature', 'Temperature in degrees Celsius'),
+        ('checksum', 'Checksum'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0, 1, 2, 3)),
+        ('bytes', 'Bytes', (4,)),
+        ('results', 'Results', (5, 6, 7)),
+    )
+
+    def putfs(self, data):
+        self.put(self.fall, self.samplenum, self.out_ann, data)
+
+    def putb(self, data):
+        self.put(self.bytepos[-1], self.samplenum, self.out_ann, data)
+
+    def putv(self, data):
+        self.put(self.bytepos[-2], self.samplenum, self.out_ann, data)
+
+    def reset(self):
+        self.state = 'WAIT FOR START LOW'
+        self.samplenum = 0
+        self.fall = 0
+        self.rise = 0
+        self.bits = []
+        self.bytepos = []
+
+    def is_valid(self, name):
+        dt = 0
+        if name.endswith('LOW'):
+            dt = self.samplenum - self.fall
+        elif name.endswith('HIGH'):
+            dt = self.samplenum - self.rise
+        if dt >= self.cnt[name]['min'] and dt <= self.cnt[name]['max']:
+            return True
+        return False
+
+    def bits2num(self, bitlist):
+        number = 0
+        for i in range(len(bitlist)):
+            number += bitlist[-1 - i] * 2**i
+        return number
+
+    def calculate_humidity(self, bitlist):
+        h = 0
+        if self.options['device'] == 'dht11':
+            h = self.bits2num(bitlist[0:8])
+        else:
+            h = self.bits2num(bitlist) / 10
+        return h
+
+    def calculate_temperature(self, bitlist):
+        t = 0
+        if self.options['device'] == 'dht11':
+            t = self.bits2num(bitlist[0:8])
+        else:
+            t = self.bits2num(bitlist[1:]) / 10
+            if bitlist[0] == 1:
+                t = -t
+        return t
+
+    def calculate_checksum(self, bitlist):
+        checksum = 0
+        for i in range(8, len(bitlist) + 1, 8):
+            checksum += self.bits2num(bitlist[i-8:i])
+        return checksum % 256
+
+    def __init__(self):
+        self.samplerate = None
+        self.reset()
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def metadata(self, key, value):
+        if key != srd.SRD_CONF_SAMPLERATE:
+            return
+        self.samplerate = value
+        # Convert microseconds to sample counts.
+        self.cnt = {}
+        for e in timing:
+            self.cnt[e] = {}
+            for t in timing[e]:
+                self.cnt[e][t] = timing[e][t] * self.samplerate / 1000000
+
+    def handle_byte(self, bit):
+        self.bits.append(bit)
+        self.putfs([2, ['Bit: %d' % bit, '%d' % bit]])
+        self.fall = self.samplenum
+        self.state = 'WAIT FOR BIT HIGH'
+        if len(self.bits) % 8 == 0:
+            byte = self.bits2num(self.bits[-8:])
+            self.putb([4, ['Byte: %#04x' % byte, '%#04x' % byte]])
+            if len(self.bits) == 16:
+                h = self.calculate_humidity(self.bits[-16:])
+                self.putv([5, ['Humidity: %.1f %%' % h, 'RH = %.1f %%' % h]])
+            elif len(self.bits) == 32:
+                t = self.calculate_temperature(self.bits[-16:])
+                self.putv([6, ['Temperature: %.1f °C' % t, 'T = %.1f °C' % t]])
+            elif len(self.bits) == 40:
+                parity = self.bits2num(self.bits[-8:])
+                if parity == self.calculate_checksum(self.bits[0:32]):
+                    self.putb([7, ['Checksum: OK', 'OK']])
+                else:
+                    self.putb([7, ['Checksum: not OK', 'NOK']])
+                self.state = 'WAIT FOR END'
+            self.bytepos.append(self.samplenum)
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, (sda,)) in data:
+            # State machine.
+            if self.state == 'WAIT FOR START LOW':
+                if sda != 0:
+                    continue
+                self.fall = self.samplenum
+                self.state = 'WAIT FOR START HIGH'
+            elif self.state == 'WAIT FOR START HIGH':
+                if sda != 1:
+                    continue
+                if self.is_valid('START LOW'):
+                    self.rise = self.samplenum
+                    self.state = 'WAIT FOR RESPONSE LOW'
+                else:
+                    self.reset()
+            elif self.state == 'WAIT FOR RESPONSE LOW':
+                if sda != 0:
+                    continue
+                if self.is_valid('START HIGH'):
+                    self.putfs([0, ['Start', 'S']])
+                    self.fall = self.samplenum
+                    self.state = 'WAIT FOR RESPONSE HIGH'
+                else:
+                    self.reset()
+            elif self.state == 'WAIT FOR RESPONSE HIGH':
+                if sda != 1:
+                    continue
+                if self.is_valid('RESPONSE LOW'):
+                    self.rise = self.samplenum
+                    self.state = 'WAIT FOR FIRST BIT'
+                else:
+                    self.reset()
+            elif self.state == 'WAIT FOR FIRST BIT':
+                if sda != 0:
+                    continue
+                if self.is_valid('RESPONSE HIGH'):
+                    self.putfs([1, ['Response', 'R']])
+                    self.fall = self.samplenum
+                    self.bytepos.append(self.samplenum)
+                    self.state = 'WAIT FOR BIT HIGH'
+                else:
+                    self.reset()
+            elif self.state == 'WAIT FOR BIT HIGH':
+                if sda != 1:
+                    continue
+                if self.is_valid('BIT LOW'):
+                    self.rise = self.samplenum
+                    self.state = 'WAIT FOR BIT LOW'
+                else:
+                    self.reset()
+            elif self.state == 'WAIT FOR BIT LOW':
+                if sda != 0:
+                    continue
+                if self.is_valid('BIT 0 HIGH'):
+                    bit = 0
+                elif self.is_valid('BIT 1 HIGH'):
+                    bit = 1
+                else:
+                    self.reset()
+                    continue
+                self.handle_byte(bit)
+            elif self.state == 'WAIT FOR END':
+                if sda != 1:
+                    continue
+                self.putfs([3, ['End', 'E']])
+                self.reset()
diff --git a/decoders/ir_nec/__init__.py b/decoders/arm_etmv3/__init__.py
similarity index 79%
copy from decoders/ir_nec/__init__.py
copy to decoders/arm_etmv3/__init__.py
index 84bf428..7955139 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/arm_etmv3/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'uart' decoder and decodes packets of
+the ARMv7m Embedded Trace Macroblock v3.x.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/arm_etmv3/pd.py b/decoders/arm_etmv3/pd.py
new file mode 100644
index 0000000..367ceb8
--- /dev/null
+++ b/decoders/arm_etmv3/pd.py
@@ -0,0 +1,564 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import subprocess
+import re
+
+# See ETMv3 Signal Protocol table 7-11: 'Encoding of Exception[8:0]'.
+exc_names = [
+    'No exception', 'IRQ1', 'IRQ2', 'IRQ3', 'IRQ4', 'IRQ5', 'IRQ6', 'IRQ7',
+    'IRQ0', 'UsageFault', 'NMI', 'SVC', 'DebugMon', 'MemManage', 'PendSV',
+    'SysTick', 'Reserved', 'Reset', 'BusFault', 'Reserved', 'Reserved'
+]
+
+for i in range(8, 496):
+    exc_names.append('IRQ%d' % i)
+
+def parse_varint(bytes):
+    '''Parse an integer where the top bit is the continuation bit.
+    Returns value and number of parsed bytes.'''
+    v = 0
+    for i, b in enumerate(bytes):
+        v |= (b & 0x7F) << (i * 7)
+        if b & 0x80 == 0:
+            return v, i+1
+    return v, len(bytes)
+
+def parse_uint(bytes):
+    '''Parse little-endian integer.'''
+    v = 0
+    for i, b in enumerate(bytes):
+        v |= b << (i * 8)
+    return v
+
+def parse_exc_info(bytes):
+    '''Parse exception information bytes from a branch packet.'''
+    if len(bytes) < 1:
+        return None
+
+    excv, exclen = parse_varint(bytes)
+    if bytes[exclen - 1] & 0x80 != 0x00:
+        return None # Exception info not complete.
+
+    if exclen == 2 and excv & (1 << 13):
+        # Exception byte 1 was skipped, fix up the decoding.
+        excv = (excv & 0x7F) | ((excv & 0x3F80) << 7)
+
+    ns = excv & 1
+    exc = ((excv >> 1) & 0x0F) | ((excv >> 7) & 0x1F0)
+    cancel = (excv >> 5) & 1
+    altisa = (excv >> 6) & 1
+    hyp = (excv >> 12) & 1
+    resume = (excv >> 14) & 0x0F
+    return (ns, exc, cancel, altisa, hyp, resume)
+
+def parse_branch_addr(bytes, ref_addr, cpu_state, branch_enc):
+    '''Parse encoded branch address.
+       Returns addr, addrlen, cpu_state, exc_info.
+       Returns None if packet is not yet complete'''
+
+    addr, addrlen = parse_varint(bytes)
+
+    if bytes[addrlen-1] & 0x80 != 0x00:
+        return None # Branch address not complete.
+
+    addr_bits = 7 * addrlen
+
+    have_exc_info = False
+    if branch_enc == 'original':
+        if addrlen == 5 and bytes[4] & 0x40:
+            have_exc_info = True
+    elif branch_enc == 'alternative':
+        addr_bits -= 1 # Top bit of address indicates exc_info.
+        if addrlen >= 2 and addr & (1 << addr_bits):
+            have_exc_info = True
+            addr &= ~(1 << addr_bits)
+
+    exc_info = None
+    if have_exc_info:
+        exc_info = parse_exc_info(bytes[addrlen:])
+        if exc_info is None:
+            return None # Exception info not complete.
+
+    if addrlen == 5:
+        # Possible change in CPU state.
+        if bytes[4] & 0xB8 == 0x08:
+            cpu_state = 'arm'
+        elif bytes[4] & 0xB0 == 0x10:
+            cpu_state = 'thumb'
+        elif bytes[4] & 0xA0 == 0x20:
+            cpu_state = 'jazelle'
+        else:
+            raise NotImplementedError('Unhandled branch byte 4: 0x%02x' % bytes[4])
+
+    # Shift the address according to current CPU state.
+    if cpu_state == 'arm':
+        addr = (addr & 0xFFFFFFFE) << 1
+        addr_bits += 1
+    elif cpu_state == 'thumb':
+        addr = addr & 0xFFFFFFFE
+    elif cpu_state == 'jazelle':
+        addr = (addr & 0xFFFFFFFFE) >> 1
+        addr_bits -= 1
+    else:
+        raise NotImplementedError('Unhandled state: ' + cpu_state)
+
+    # If the address wasn't full, fill in with the previous address.
+    if addrlen < 5:
+        addr |= ref_addr & (0xFFFFFFFF << addr_bits)
+
+    return addr, addrlen, cpu_state, exc_info
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'arm_etmv3'
+    name = 'ARM ETMv3'
+    longname = 'ARM Embedded Trace Macroblock'
+    desc = 'Decode ETM instruction trace packets.'
+    license = 'gplv2+'
+    inputs = ['uart']
+    outputs = ['arm_etmv3']
+    annotations = (
+        ('trace', 'Trace info'),
+        ('branch', 'Branches'),
+        ('exception', 'Exceptions'),
+        ('execution', 'Instruction execution'),
+        ('data', 'Data access'),
+        ('pc', 'Program counter'),
+        ('instr_e', 'Executed instructions'),
+        ('instr_n', 'Not executed instructions'),
+        ('source', 'Source code'),
+        ('location', 'Current location'),
+        ('function', 'Current function'),
+    )
+    annotation_rows = (
+        ('trace', 'Trace info', (0,)),
+        ('flow', 'Code flow', (1, 2, 3,)),
+        ('data', 'Data access', (4,)),
+        ('pc', 'Program counter', (5,)),
+        ('instruction', 'Instructions', (6, 7,)),
+        ('source', 'Source code', (8,)),
+        ('location', 'Current location', (9,)),
+        ('function', 'Current function', (10,)),
+    )
+    options = (
+        {'id': 'objdump', 'desc': 'objdump path',
+            'default': 'arm-none-eabi-objdump'},
+        {'id': 'objdump_opts', 'desc': 'objdump options',
+            'default': '-lSC'},
+        {'id': 'elffile', 'desc': '.elf path',
+            'default': ''},
+        {'id': 'branch_enc', 'desc': 'Branch encoding',
+            'default': 'alternative', 'values': ('alternative', 'original')},
+    )
+
+    def __init__(self):
+        self.buf = []
+        self.syncbuf = []
+        self.prevsample = 0
+        self.last_branch = 0
+        self.cpu_state = 'arm'
+        self.current_pc = 0
+        self.current_loc = None
+        self.current_func = None
+        self.next_instr_lookup = {}
+        self.file_lookup = {}
+        self.func_lookup = {}
+        self.disasm_lookup = {}
+        self.source_lookup = {}
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.load_objdump()
+
+    def load_objdump(self):
+        '''Parse disassembly obtained from objdump into two tables:
+        next_instr_lookup: Find the next PC addr from current PC.
+        disasm_lookup: Find the instruction text from current PC.
+        source_lookup: Find the source code line from current PC.
+        '''
+        if not (self.options['objdump'] and self.options['elffile']):
+            return
+
+        opts = [self.options['objdump']]
+        opts += self.options['objdump_opts'].split()
+        opts += [self.options['elffile']]
+
+        try:
+            disasm = subprocess.check_output(opts)
+        except subprocess.CalledProcessError:
+            return
+
+        disasm = disasm.decode('utf-8', 'replace')
+
+        instpat = re.compile('\s*([0-9a-fA-F]+):\t+([0-9a-fA-F ]+)\t+([a-zA-Z][^;]+)\s*;?.*')
+        branchpat = re.compile('(b|bl|b..|bl..|cbnz|cbz)(?:\.[wn])?\s+(?:r[0-9]+,\s*)?([0-9a-fA-F]+)')
+        filepat = re.compile('[^\s]+[/\\\\]([a-zA-Z0-9._-]+:[0-9]+)(?:\s.*)?')
+        funcpat = re.compile('[0-9a-fA-F]+\s*<([^>]+)>:.*')
+
+        prev_src = ''
+        prev_file = ''
+        prev_func = ''
+
+        for line in disasm.split('\n'):
+            m = instpat.match(line)
+            if m:
+                addr = int(m.group(1), 16)
+                raw = m.group(2)
+                disas = m.group(3).strip().replace('\t', ' ')
+                self.disasm_lookup[addr] = disas
+                self.source_lookup[addr] = prev_src
+                self.file_lookup[addr] = prev_file
+                self.func_lookup[addr] = prev_func
+
+                # Next address in direct sequence.
+                ilen = len(raw.replace(' ', '')) // 2
+                next_n = addr + ilen
+
+                # Next address if branch is taken.
+                bm = branchpat.match(disas)
+                if bm:
+                    next_e = int(bm.group(2), 16)
+                else:
+                    next_e = next_n
+
+                self.next_instr_lookup[addr] = (next_n, next_e)
+            else:
+                m = funcpat.match(line)
+                if m:
+                    prev_func = m.group(1)
+                    prev_src = None
+                else:
+                    m = filepat.match(line)
+                    if m:
+                        prev_file = m.group(1)
+                        prev_src = None
+                    else:
+                        prev_src = line.strip()
+
+    def flush_current_loc(self):
+        if self.current_loc is not None:
+            ss, es, loc, src = self.current_loc
+            if loc:
+                self.put(ss, es, self.out_ann, [9, [loc]])
+            if src:
+                self.put(ss, es, self.out_ann, [8, [src]])
+            self.current_loc = None
+
+    def flush_current_func(self):
+        if self.current_func is not None:
+            ss, es, func = self.current_func
+            if func:
+                self.put(ss, es, self.out_ann, [10, [func]])
+            self.current_func = None
+
+    def instructions_executed(self, exec_status):
+        '''Advance program counter based on executed instructions.
+        Argument is a list of False for not executed and True for executed
+        instructions.
+        '''
+
+        if len(exec_status) == 0:
+            return
+
+        tdelta = max(1, (self.prevsample - self.startsample) / len(exec_status))
+
+        for i, exec_status in enumerate(exec_status):
+            pc = self.current_pc
+            default_next = pc + 2 if self.cpu_state == 'thumb' else pc + 4
+            target_n, target_e = self.next_instr_lookup.get(pc, (default_next, default_next))
+            ss = self.startsample + round(tdelta * i)
+            es = self.startsample + round(tdelta * (i+1))
+
+            self.put(ss, es, self.out_ann,
+                     [5, ['PC 0x%08x' % pc, '0x%08x' % pc, '%08x' % pc]])
+
+            new_loc = self.file_lookup.get(pc)
+            new_src = self.source_lookup.get(pc)
+            new_dis = self.disasm_lookup.get(pc)
+            new_func = self.func_lookup.get(pc)
+
+            # Report source line only when it changes.
+            if self.current_loc is not None:
+                if new_loc != self.current_loc[2] or new_src != self.current_loc[3]:
+                    self.flush_current_loc()
+
+            if self.current_loc is None:
+                self.current_loc = [ss, es, new_loc, new_src]
+            else:
+                self.current_loc[1] = es
+
+            # Report function name only when it changes.
+            if self.current_func is not None:
+                if new_func != self.current_func[2]:
+                    self.flush_current_func()
+
+            if self.current_func is None:
+                self.current_func = [ss, es, new_func]
+            else:
+                self.current_func[1] = es
+
+            # Report instruction every time.
+            if new_dis:
+                if exec_status:
+                    a = [6, ['Executed: ' + new_dis, new_dis, new_dis.split()[0]]]
+                else:
+                    a = [7, ['Not executed: ' + new_dis, new_dis, new_dis.split()[0]]]
+                self.put(ss, es, self.out_ann, a)
+
+            if exec_status:
+                self.current_pc = target_e
+            else:
+                self.current_pc = target_n
+
+    def get_packet_type(self, byte):
+        '''Identify packet type based on its first byte.
+           See ARM IHI0014Q section "ETMv3 Signal Protocol" "Packet Types"
+        '''
+        if byte & 0x01 == 0x01:
+            return 'branch'
+        elif byte == 0x00:
+            return 'a_sync'
+        elif byte == 0x04:
+            return 'cyclecount'
+        elif byte == 0x08:
+            return 'i_sync'
+        elif byte == 0x0C:
+            return 'trigger'
+        elif byte & 0xF3 in (0x20, 0x40, 0x60):
+            return 'ooo_data'
+        elif byte == 0x50:
+            return 'store_failed'
+        elif byte == 0x70:
+            return 'i_sync'
+        elif byte & 0xDF in (0x54, 0x58, 0x5C):
+            return 'ooo_place'
+        elif byte == 0x3C:
+            return 'vmid'
+        elif byte & 0xD3 == 0x02:
+            return 'data'
+        elif byte & 0xFB == 0x42:
+            return 'timestamp'
+        elif byte == 0x62:
+            return 'data_suppressed'
+        elif byte == 0x66:
+            return 'ignore'
+        elif byte & 0xEF == 0x6A:
+            return 'value_not_traced'
+        elif byte == 0x6E:
+            return 'context_id'
+        elif byte == 0x76:
+            return 'exception_exit'
+        elif byte == 0x7E:
+            return 'exception_entry'
+        elif byte & 0x81 == 0x80:
+            return 'p_header'
+        else:
+            return 'unknown'
+
+    def fallback(self, buf):
+        ptype = self.get_packet_type(buf[0])
+        return [0, ['Unhandled ' + ptype + ': ' + ' '.join(['%02x' % b for b in buf])]]
+
+    def handle_a_sync(self, buf):
+        if buf[-1] == 0x80:
+            return [0, ['Synchronization']]
+
+    def handle_exception_exit(self, buf):
+        return [2, ['Exception exit']]
+
+    def handle_exception_entry(self, buf):
+        return [2, ['Exception entry']]
+
+    def handle_i_sync(self, buf):
+        contextid_bytes = 0 # This is the default ETM config.
+
+        if len(buf) < 6:
+            return None # Packet definitely not full yet.
+
+        if buf[0] == 0x08: # No cycle count.
+            cyclecount = None
+            idx = 1 + contextid_bytes # Index to info byte.
+        elif buf[0] == 0x70: # With cycle count.
+            cyclecount, cyclen = parse_varint(buf[1:6])
+            idx = 1 + cyclen + contextid_bytes
+
+        if len(buf) <= idx + 4:
+            return None
+        infobyte = buf[idx]
+        addr = parse_uint(buf[idx+1:idx+5])
+
+        reasoncode = (infobyte >> 5) & 3
+        reason = ('Periodic', 'Tracing enabled', 'After overflow', 'Exit from debug')[reasoncode]
+        jazelle = (infobyte >> 4) & 1
+        nonsec = (infobyte >> 3) & 1
+        altisa = (infobyte >> 2) & 1
+        hypervisor = (infobyte >> 1) & 1
+        thumb = addr & 1
+        addr &= 0xFFFFFFFE
+
+        if reasoncode == 0 and self.current_pc != addr:
+            self.put(self.startsample, self.prevsample, self.out_ann,
+                     [0, ['WARN: Unexpected PC change 0x%08x -> 0x%08x' % \
+                     (self.current_pc, addr)]])
+        elif reasoncode != 0:
+            # Reset location when the trace has been interrupted.
+            self.flush_current_loc()
+            self.flush_current_func()
+
+        self.last_branch = addr
+        self.current_pc = addr
+
+        if jazelle:
+            self.cpu_state = 'jazelle'
+        elif thumb:
+            self.cpu_state = 'thumb'
+        else:
+            self.cpu_state = 'arm'
+
+        cycstr = ''
+        if cyclecount is not None:
+            cycstr = ', cyclecount %d' % cyclecount
+
+        if infobyte & 0x80: # LSIP packet
+            self.put(self.startsample, self.prevsample, self.out_ann,
+                     [0, ['WARN: LSIP I-Sync packet not implemented']])
+
+        return [0, ['I-Sync: %s, PC 0x%08x, %s state%s' % \
+                    (reason, addr, self.cpu_state, cycstr), \
+                    'I-Sync: %s 0x%08x' % (reason, addr)]]
+
+    def handle_trigger(self, buf):
+        return [0, ['Trigger event', 'Trigger']]
+
+    def handle_p_header(self, buf):
+        # Only non cycle-accurate mode supported.
+        if buf[0] & 0x83 == 0x80:
+            n = (buf[0] >> 6) & 1
+            e = (buf[0] >> 2) & 15
+
+            self.instructions_executed([1] * e + [0] * n)
+
+            if n:
+                return [3, ['%d instructions executed, %d skipped due to ' \
+                            'condition codes' % (e, n),
+                            '%d ins exec, %d skipped' % (e, n),
+                            '%dE,%dN' % (e, n)]]
+            else:
+                return [3, ['%d instructions executed' % e,
+                            '%d ins exec' % e, '%dE' % e]]
+        elif buf[0] & 0xF3 == 0x82:
+            i1 = (buf[0] >> 3) & 1
+            i2 = (buf[0] >> 2) & 1
+            self.instructions_executed([not i1, not i2])
+            txt1 = ('executed', 'skipped')
+            txt2 = ('E', 'S')
+            return [3, ['Instruction 1 %s, instruction 2 %s' % (txt1[i1], txt1[i2]),
+                        'I1 %s, I2 %s' % (txt2[i1], txt2[i2]),
+                        '%s,%s' % (txt2[i1], txt2[i2])]]
+        else:
+            return self.fallback(buf)
+
+    def handle_branch(self, buf):
+        if buf[-1] & 0x80 != 0x00:
+            return None # Not complete yet.
+
+        brinfo = parse_branch_addr(buf, self.last_branch, self.cpu_state,
+                                   self.options['branch_enc'])
+
+        if brinfo is None:
+            return None # Not complete yet.
+
+        addr, addrlen, cpu_state, exc_info = brinfo
+        self.last_branch = addr
+        self.current_pc = addr
+
+        txt = ''
+
+        if cpu_state != self.cpu_state:
+            txt += ', to %s state' % cpu_state
+            self.cpu_state = cpu_state
+
+        annidx = 1
+
+        if exc_info:
+            annidx = 2
+            ns, exc, cancel, altisa, hyp, resume = exc_info
+            if ns:
+                txt += ', to non-secure state'
+            if exc:
+                if exc < len(exc_names):
+                    txt += ', exception %s' % exc_names[exc]
+                else:
+                    txt += ', exception 0x%02x' % exc
+            if cancel:
+                txt += ', instr cancelled'
+            if altisa:
+                txt += ', to AltISA'
+            if hyp:
+                txt += ', to hypervisor'
+            if resume:
+                txt += ', instr resume 0x%02x' % resume
+
+        return [annidx, ['Branch to 0x%08x%s' % (addr, txt),
+                         'B 0x%08x%s' % (addr, txt)]]
+
+    def decode(self, ss, es, data):
+        ptype, rxtx, pdata = data
+
+        if ptype != 'DATA':
+            return
+
+        # Reset packet if there is a long pause between bytes.
+        # This helps getting the initial synchronization.
+        self.byte_len = es - ss
+        if ss - self.prevsample > 16 * self.byte_len:
+            self.flush_current_loc()
+            self.flush_current_func()
+            self.buf = []
+        self.prevsample = es
+
+        self.buf.append(pdata[0])
+
+        # Store the start time of the packet.
+        if len(self.buf) == 1:
+            self.startsample = ss
+
+        # Keep separate buffer for detection of sync packets.
+        # Sync packets override everything else, so that we can regain sync
+        # even if some packets are corrupted.
+        self.syncbuf = self.syncbuf[-4:] + [pdata[0]]
+        if self.syncbuf == [0x00, 0x00, 0x00, 0x00, 0x80]:
+            self.buf = self.syncbuf
+            self.syncbuf = []
+
+        # See if it is ready to be decoded.
+        ptype = self.get_packet_type(self.buf[0])
+        if hasattr(self, 'handle_' + ptype):
+            func = getattr(self, 'handle_' + ptype)
+            data = func(self.buf)
+        else:
+            data = self.fallback(self.buf)
+
+        if data is not None:
+            if data:
+                self.put(self.startsample, es, self.out_ann, data)
+            self.buf = []
diff --git a/decoders/dcf77/__init__.py b/decoders/arm_itm/__init__.py
similarity index 76%
copy from decoders/dcf77/__init__.py
copy to decoders/arm_itm/__init__.py
index 04805c2..d9789a4 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/arm_itm/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
 ##
 ## 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
@@ -19,12 +19,8 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
-
-Details:
-http://en.wikipedia.org/wiki/DCF77
+This decoder stacks on top of the 'uart' or 'arm_tpiu' PD and decodes the 
+ARM Cortex-M processor trace data from Instrumentation Trace Macroblock.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/arm_itm/pd.py b/decoders/arm_itm/pd.py
new file mode 100644
index 0000000..384999c
--- /dev/null
+++ b/decoders/arm_itm/pd.py
@@ -0,0 +1,370 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import string
+import subprocess
+import re
+
+ARM_EXCEPTIONS = {
+    0: 'Thread',
+    1: 'Reset',
+    2: 'NMI',
+    3: 'HardFault',
+    4: 'MemManage',
+    5: 'BusFault',
+    6: 'UsageFault',
+    11: 'SVCall',
+    12: 'Debug Monitor',
+    14: 'PendSV',
+    15: 'SysTick',
+}
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'arm_itm'
+    name = 'ARM ITM'
+    longname = 'ARM Instrumentation Trace Macroblock'
+    desc = 'Trace data from Cortex-M / ARMv7m ITM module.'
+    license = 'gplv2+'
+    inputs = ['uart']
+    outputs = ['arm_itm']
+    options = (
+        {'id': 'objdump', 'desc': 'objdump path',
+            'default': 'arm-none-eabi-objdump'},
+        {'id': 'objdump_opts', 'desc': 'objdump options',
+            'default': '-lSC'},
+        {'id': 'elffile', 'desc': '.elf path',
+            'default': ''},
+    )
+    annotations = (
+        ('trace', 'Trace information'),
+        ('timestamp', 'Timestamp'),
+        ('software', 'Software message'),
+        ('dwt_event', 'DWT event'),
+        ('dwt_watchpoint', 'DWT watchpoint'),
+        ('dwt_exc', 'Exception trace'),
+        ('dwt_pc', 'Program counter'),
+        ('mode_thread', 'Current mode: thread'),
+        ('mode_irq', 'Current mode: IRQ'),
+        ('mode_exc', 'Current mode: Exception'),
+        ('location', 'Current location'),
+        ('function', 'Current function'),
+    )
+    annotation_rows = (
+        ('trace', 'Trace information', (0, 1)),
+        ('software', 'Software trace', (2,)),
+        ('dwt_event', 'DWT event', (3,)),
+        ('dwt_watchpoint', 'DWT watchpoint', (4,)),
+        ('dwt_exc', 'Exception trace', (5,)),
+        ('dwt_pc', 'Program counter', (6,)),
+        ('mode', 'Current mode', (7, 8, 9)),
+        ('location', 'Current location', (10,)),
+        ('function', 'Current function', (11,)),
+    )
+
+    def __init__(self):
+        self.buf = []
+        self.syncbuf = []
+        self.swpackets = {}
+        self.prevsample = 0
+        self.dwt_timestamp = 0
+        self.current_mode = None
+        self.file_lookup = {}
+        self.func_lookup = {}
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.load_objdump()
+
+    def load_objdump(self):
+        '''Parse disassembly obtained from objdump into a lookup tables'''
+        if not (self.options['objdump'] and self.options['elffile']):
+            return
+
+        opts = [self.options['objdump']]
+        opts += self.options['objdump_opts'].split()
+        opts += [self.options['elffile']]
+
+        try:
+            disasm = subprocess.check_output(opts)
+        except subprocess.CalledProcessError:
+            return
+
+        disasm = disasm.decode('utf-8', 'replace')
+
+        instpat = re.compile('\s*([0-9a-fA-F]+):\t+([0-9a-fA-F ]+)\t+([a-zA-Z][^;]+)\s*;?.*')
+        filepat = re.compile('[^\s]+[/\\\\]([a-zA-Z0-9._-]+:[0-9]+)(?:\s.*)?')
+        funcpat = re.compile('[0-9a-fA-F]+\s*<([^>]+)>:.*')
+
+        prev_file = ''
+        prev_func = ''
+
+        for line in disasm.split('\n'):
+            m = instpat.match(line)
+            if m:
+                addr = int(m.group(1), 16)
+                self.file_lookup[addr] = prev_file
+                self.func_lookup[addr] = prev_func
+            else:
+                m = funcpat.match(line)
+                if m:
+                    prev_func = m.group(1)
+                else:
+                    m = filepat.match(line)
+                    if m:
+                        prev_file = m.group(1)
+
+    def get_packet_type(self, byte):
+        '''Identify packet type based on its first byte.
+           See ARMv7-M_ARM.pdf section "Debug ITM and DWT" "Packet Types"
+        '''
+        if byte & 0x7F == 0:
+            return 'sync'
+        elif byte == 0x70:
+            return 'overflow'
+        elif byte & 0x0F == 0 and byte & 0xF0 != 0:
+            return 'timestamp'
+        elif byte & 0x0F == 0x08:
+            return 'sw_extension'
+        elif byte & 0x0F == 0x0C:
+            return 'hw_extension'
+        elif byte & 0x0F == 0x04:
+            return 'reserved'
+        elif byte & 0x04 == 0x00:
+            return 'software'
+        else:
+            return 'hardware'
+
+    def mode_change(self, new_mode):
+        if self.current_mode is not None:
+            start, mode = self.current_mode
+            if mode.startswith('Thread'):
+                ann_idx = 7
+            elif mode.startswith('IRQ'):
+                ann_idx = 8
+            else:
+                ann_idx = 9
+            self.put(start, self.startsample, self.out_ann, [ann_idx, [mode]])
+
+        if new_mode is None:
+            self.current_mode = None
+        else:
+            self.current_mode = (self.startsample, new_mode)
+
+    def location_change(self, pc):
+        new_loc = self.file_lookup.get(pc)
+        new_func = self.func_lookup.get(pc)
+        ss = self.startsample
+        es = self.prevsample
+
+        if new_loc is not None:
+            self.put(ss, es, self.out_ann, [10, [new_loc]])
+
+        if new_func is not None:
+            self.put(ss, es, self.out_ann, [11, [new_func]])
+
+    def fallback(self, buf):
+        ptype = self.get_packet_type(buf[0])
+        return [0, [('Unhandled %s: ' % ptype) + ' '.join(['%02x' % b for b in buf])]]
+
+    def handle_overflow(self, buf):
+        return [0, ['Overflow']]
+
+    def handle_hardware(self, buf):
+        '''Handle packets from hardware source, i.e. DWT block.'''
+        plen = (0, 1, 2, 4)[buf[0] & 0x03]
+        pid = buf[0] >> 3
+        if len(buf) != plen + 1:
+            return None # Not complete yet.
+
+        if pid == 0:
+            text = 'DWT events:'
+            if buf[1] & 0x20:
+                text += ' Cyc'
+            if buf[1] & 0x10:
+                text += ' Fold'
+            if buf[1] & 0x08:
+                text += ' LSU'
+            if buf[1] & 0x04:
+                text += ' Sleep'
+            if buf[1] & 0x02:
+                text += ' Exc'
+            if buf[1] & 0x01:
+                text += ' CPI'
+            return [3, [text]]
+        elif pid == 1:
+            excnum = ((buf[2] & 1) << 8) | buf[1]
+            event = (buf[2] >> 4)
+            excstr = ARM_EXCEPTIONS.get(excnum, 'IRQ %d' % (excnum - 16))
+            if event == 1:
+                self.mode_change(excstr)
+                return [5, ['Enter: ' + excstr, 'E ' + excstr]]
+            elif event == 2:
+                self.mode_change(None)
+                return [5, ['Exit: ' + excstr, 'X ' + excstr]]
+            elif event == 3:
+                self.mode_change(excstr)
+                return [5, ['Resume: ' + excstr, 'R ' + excstr]]
+        elif pid == 2:
+            pc = buf[1] | (buf[2] << 8) | (buf[3] << 16) | (buf[4] << 24)
+            self.location_change(pc)
+            return [6, ['PC: 0x%08x' % pc]]
+        elif (buf[0] & 0xC4) == 0x84:
+            comp = (buf[0] & 0x30) >> 4
+            what = 'Read' if (buf[0] & 0x08) == 0 else 'Write'
+            if plen == 1:
+                data = '0x%02x' % (buf[1])
+            elif plen == 2:
+                data = '0x%04x' % (buf[1] | (buf[2] << 8))
+            else:
+                data = '0x%08x' % (buf[1] | (buf[2] << 8) | (buf[3] << 16) | (buf[4] << 24))
+            return [4, ['Watchpoint %d: %s data %s' % (comp, what, data),
+                        'WP%d: %s %s' % (comp, what[0], data)]]
+        elif (buf[0] & 0xCF) == 0x47:
+            comp = (buf[0] & 0x30) >> 4
+            addr = buf[1] | (buf[2] << 8) | (buf[3] << 16) | (buf[4] << 24)
+            self.location_change(addr)
+            return [4, ['Watchpoint %d: PC 0x%08x' % (comp, addr),
+                        'WP%d: PC 0x%08x' % (comp, addr)]]
+        elif (buf[0] & 0xCF) == 0x4E:
+            comp = (buf[0] & 0x30) >> 4
+            offset = buf[1] | (buf[2] << 8)
+            return [4, ['Watchpoint %d: address 0x????%04x' % (comp, offset),
+                        'WP%d: A 0x%04x' % (comp, offset)]]
+
+        return self.fallback(buf)
+
+    def handle_software(self, buf):
+        '''Handle packets generated by software running on the CPU.'''
+        plen = (0, 1, 2, 4)[buf[0] & 0x03]
+        pid = buf[0] >> 3
+        if len(buf) != plen + 1:
+            return None # Not complete yet.
+
+        if plen == 1 and chr(buf[1]) in string.printable:
+            self.add_delayed_sw(pid, chr(buf[1]))
+            return [] # Handled but no data to output.
+
+        self.push_delayed_sw()
+
+        if plen == 1:
+            return [2, ['%d: 0x%02x' % (pid, buf[1])]]
+        elif plen == 2:
+            return [2, ['%d: 0x%02x%02x' % (pid, buf[2], buf[1])]]
+        elif plen == 4:
+            return [2, ['%d: 0x%02x%02x%02x%02x' % (pid, buf[4], buf[3], buf[2], buf[1])]]
+
+    def handle_timestamp(self, buf):
+        '''Handle timestamp packets, which indicate the time of some DWT event packet.'''
+        if buf[-1] & 0x80 != 0:
+            return None # Not complete yet.
+
+        if buf[0] & 0x80 == 0:
+            tc = 0
+            ts = buf[0] >> 4
+        else:
+            tc = (buf[0] & 0x30) >> 4
+            ts = buf[1] & 0x7F
+            if len(buf) > 2:
+                ts |= (buf[2] & 0x7F) << 7
+            if len(buf) > 3:
+                ts |= (buf[3] & 0x7F) << 14
+            if len(buf) > 4:
+                ts |= (buf[4] & 0x7F) << 21
+
+        self.dwt_timestamp += ts
+
+        if tc == 0:
+            msg = '(exact)'
+        elif tc == 1:
+            msg = '(timestamp delayed)'
+        elif tc == 2:
+            msg = '(event delayed)'
+        elif tc == 3:
+            msg = '(event and timestamp delayed)'
+
+        return [1, ['Timestamp: %d %s' % (self.dwt_timestamp, msg)]]
+
+    def add_delayed_sw(self, pid, c):
+        '''We join printable characters from software source so that printed
+        strings are easy to read. Joining is done by PID so that different
+        sources do not get confused with each other.'''
+        if self.swpackets.get(pid) is not None:
+            self.swpackets[pid][1] = self.prevsample
+            self.swpackets[pid][2] += c
+        else:
+            self.swpackets[pid] = [self.startsample, self.prevsample, c]
+
+    def push_delayed_sw(self):
+        for pid, packet in self.swpackets.items():
+            if packet is None:
+                continue
+            ss, prevtime, text = packet
+            # Heuristic criterion: Text has ended if at least 16 byte
+            # durations after previous received byte. Actual delay depends
+            # on printf implementation on target.
+            if self.prevsample - prevtime > 16 * self.byte_len:
+                self.put(ss, prevtime, self.out_ann, [2, ['%d: "%s"' % (pid, text)]])
+                self.swpackets[pid] = None
+
+    def decode(self, ss, es, data):
+        ptype, rxtx, pdata = data
+
+        # For now, ignore all UART packets except the actual data packets.
+        if ptype != 'DATA':
+            return
+
+        self.byte_len = es - ss
+
+        # Reset packet if there is a long pause between bytes.
+        # TPIU framing can introduce small pauses, but more than 1 frame
+        # should reset packet.
+        if ss - self.prevsample > 16 * self.byte_len:
+            self.push_delayed_sw()
+            self.buf = []
+        self.prevsample = es
+
+        # Build up the current packet byte by byte.
+        self.buf.append(pdata[0])
+
+        # Store the start time of the packet.
+        if len(self.buf) == 1:
+            self.startsample = ss
+
+        # Keep separate buffer for detection of sync packets.
+        # Sync packets override everything else, so that we can regain sync
+        # even if some packets are corrupted.
+        self.syncbuf = self.syncbuf[-5:] + [pdata[0]]
+        if self.syncbuf == [0, 0, 0, 0, 0, 0x80]:
+            self.buf = self.syncbuf
+
+        # See if it is ready to be decoded.
+        ptype = self.get_packet_type(self.buf[0])
+        if hasattr(self, 'handle_' + ptype):
+            func = getattr(self, 'handle_' + ptype)
+            data = func(self.buf)
+        else:
+            data = self.fallback(self.buf)
+
+        if data is not None:
+            if data:
+                self.put(self.startsample, es, self.out_ann, data)
+            self.buf = []
diff --git a/decoders/dcf77/__init__.py b/decoders/arm_tpiu/__init__.py
similarity index 68%
copy from decoders/dcf77/__init__.py
copy to decoders/arm_tpiu/__init__.py
index 04805c2..4958df8 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/arm_tpiu/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
 ##
 ## 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
@@ -19,12 +19,10 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
-
-Details:
-http://en.wikipedia.org/wiki/DCF77
+This decoder stacks on top of the 'uart' decoder and decodes the frame format
+of ARMv7m Trace Port Interface Unit. It filters the data coming from various
+trace sources (such as ARMv7m ITM and ETM blocks) into separate streams that
+can be further decoded by other PDs.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/arm_tpiu/pd.py b/decoders/arm_tpiu/pd.py
new file mode 100644
index 0000000..d111311
--- /dev/null
+++ b/decoders/arm_tpiu/pd.py
@@ -0,0 +1,128 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'arm_tpiu'
+    name = 'ARM TPIU'
+    longname = 'ARM Trace Port Interface Unit'
+    desc = 'Filter TPIU formatted trace data into separate streams.'
+    license = 'gplv2+'
+    inputs = ['uart']
+    outputs = ['uart'] # Emulate uart output so that arm_itm/arm_etm can stack.
+    options = (
+        {'id': 'stream', 'desc': 'Stream index', 'default': 1},
+        {'id': 'sync_offset', 'desc': 'Initial sync offset', 'default': 0},
+    )
+    annotations = (
+        ('stream', 'Current stream'),
+        ('data', 'Stream data'),
+    )
+    annotation_rows = (
+        ('stream', 'Current stream', (0,)),
+        ('data', 'Stream data', (1,)),
+    )
+
+    def __init__(self):
+        self.buf = []
+        self.syncbuf = []
+        self.prevsample = 0
+        self.stream = 0
+        self.ss_stream = None
+        self.bytenum = 0
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+
+    def stream_changed(self, ss, stream):
+        if self.stream != stream:
+            if self.stream != 0:
+                self.put(self.ss_stream, ss, self.out_ann,
+                         [0, ['Stream %d' % self.stream, 'S%d' % self.stream]])
+            self.stream = stream
+            self.ss_stream = ss
+
+    def emit_byte(self, ss, es, byte):
+        if self.stream == self.options['stream']:
+            self.put(ss, es, self.out_ann, [1, ['0x%02x' % byte]])
+            self.put(ss, es, self.out_python, ['DATA', 0, (byte, [])])
+
+    def process_frame(self, buf):
+        # Byte 15 contains the lowest bits of bytes 0, 2, ... 14.
+        lowbits = buf[15][2]
+
+        for i in range(0, 15, 2):
+            # Odd bytes can be stream ID or data.
+            delayed_stream_change = None
+            lowbit = (lowbits >> (i // 2)) & 0x01
+            if buf[i][2] & 0x01 != 0:
+                if lowbit:
+                    delayed_stream_change = buf[i][2] >> 1
+                else:
+                    self.stream_changed(buf[i][0], buf[i][2] >> 1)
+            else:
+                byte = buf[i][2] | lowbit
+                self.emit_byte(buf[i][0], buf[i][1], byte)
+
+            # Even bytes are always data.
+            if i < 14:
+                self.emit_byte(buf[i+1][0], buf[i+1][1], buf[i+1][2])
+
+            # The stream change can be delayed to occur after the data byte.
+            if delayed_stream_change is not None:
+                self.stream_changed(buf[i+1][1], delayed_stream_change)
+
+    def decode(self, ss, es, data):
+        ptype, rxtx, pdata = data
+
+        if ptype != 'DATA':
+            return
+
+        # Reset packet if there is a long pause between bytes.
+        self.byte_len = es - ss
+        if ss - self.prevsample > self.byte_len:
+            self.buf = []
+        self.prevsample = es
+
+        self.buf.append((ss, es, pdata[0]))
+        self.bytenum += 1
+
+        # Allow skipping N first bytes of the data. By adjusting the sync
+        # value, one can get initial synchronization as soon as the trace
+        # starts.
+        if self.bytenum < self.options['sync_offset']:
+            self.buf = []
+            return
+
+        # Keep separate buffer for detection of sync packets.
+        # Sync packets override everything else, so that we can regain sync
+        # even if some packets are corrupted.
+        self.syncbuf = self.syncbuf[-3:] + [pdata[0]]
+        if self.syncbuf == [0xFF, 0xFF, 0xFF, 0x7F]:
+            self.buf = []
+            self.syncbuf = []
+            return
+
+        if len(self.buf) == 16:
+            self.process_frame(self.buf)
+            self.buf = []
diff --git a/decoders/dcf77/__init__.py b/decoders/aud/__init__.py
similarity index 65%
copy from decoders/dcf77/__init__.py
copy to decoders/aud/__init__.py
index 04805c2..aaa31ff 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/aud/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 fenugrec <fenugrec users.sourceforge.net>
 ##
 ## 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
@@ -19,12 +19,14 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This protocol decoder decodes the AUD (Advanced User Debugger) interface
+of certain Renesas / Hitachi microcontrollers, when set in Branch Trace mode.
+
+AUD has two modes, this PD currently only supports "Branch Trace" mode.
 
 Details:
-http://en.wikipedia.org/wiki/DCF77
+http://www.renesas.eu/products/mpumcu/superh/sh7050/sh7058/Documentation.jsp
+("rej09b0046 - SH7058 Hardware manual")
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/aud/pd.py b/decoders/aud/pd.py
new file mode 100644
index 0000000..a5330f9
--- /dev/null
+++ b/decoders/aud/pd.py
@@ -0,0 +1,114 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 fenugrec <fenugrec users.sourceforge.net>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+# TODO:
+#  - Annotations are very crude and could be improved.
+#  - Annotate every nibble? Would give insight on interrupted shifts.
+#  - Annotate invalid "command" nibbles while SYNC==1?
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'aud'
+    name = 'AUD'
+    longname = 'Advanced User Debugger'
+    desc = 'Renesas/Hitachi Advanced User Debugger (AUD) protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['aud']
+    channels = (
+        {'id': 'audck', 'name': 'AUDCK', 'desc': 'AUD clock'},
+        {'id': 'naudsync', 'name': 'nAUDSYNC', 'desc': 'AUD sync'},
+        {'id': 'audata3', 'name': 'AUDATA3', 'desc': 'AUD data line 3'},
+        {'id': 'audata2', 'name': 'AUDATA2', 'desc': 'AUD data line 2'},
+        {'id': 'audata1', 'name': 'AUDATA1', 'desc': 'AUD data line 1'},
+        {'id': 'audata0', 'name': 'AUDATA0', 'desc': 'AUD data line 0'},
+    )
+    annotations = (
+        ('dest', 'Destination address'),
+    )
+
+    def __init__(self):
+        self.ncnt = 0
+        self.nmax = 0
+        self.addr = 0
+        self.lastaddr = 0
+        self.samplenum = 0
+        self.oldclk = 0
+        self.ss = 0
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putx(self, data):
+        self.put(self.ss, self.samplenum, self.out_ann, data)
+
+    def find_clk_edge(self, clk, sync, datapins):
+        # Ignore sample if there's no edge.
+        if clk == self.oldclk:
+            return
+        self.oldclk = clk
+        # Ignore falling edges.
+        if clk == 0:
+            return
+
+        # Reconstruct nibble.
+        nib = 0
+        for i in range(4):
+            nib |= datapins[3-i] << i
+
+        # sync == 1: annotate if finished; update cmd.
+        # TODO: Annotate idle level (nibble = 0x03 && SYNC=1).
+        if sync == 1:
+            if (self.ncnt == self.nmax) and (self.nmax != 0):
+                # Done shifting an address: annotate.
+                self.putx([0, ['0x%08X' % self.addr]])
+                self.lastaddr = self.addr
+
+            self.ncnt = 0
+            self.addr = self.lastaddr
+            self.ss = self.samplenum
+            if nib == 0x08:
+                self.nmax = 1
+            elif nib == 0x09:
+                self.nmax = 2
+            elif nib == 0x0a:
+                self.nmax = 4
+            elif nib == 0x0b:
+                self.nmax = 8
+            else:
+                # Undefined or idle.
+                self.nmax = 0
+        else:
+            # sync == 0, valid cmd: start or continue shifting in nibbles.
+            if (self.nmax > 0):
+                # Clear tgt nibble.
+                self.addr &= ~(0x0F << (self.ncnt * 4))
+                # Set nibble.
+                self.addr |= nib << (self.ncnt * 4)
+                self.ncnt += 1
+
+    def decode(self, ss, es, data):
+        for (self.samplenum, pins) in data:
+            clk = pins[0]
+            sync = pins[1]
+            d = pins[2:]
+            self.find_clk_edge(clk, sync, d)
diff --git a/decoders/avr_isp/__init__.py b/decoders/avr_isp/__init__.py
index 4c4a900..75a9fe2 100644
--- a/decoders/avr_isp/__init__.py
+++ b/decoders/avr_isp/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'spi' PD and decodes the In-System
 Programming (ISP) protocol of some Atmel AVR 8-bit microcontrollers.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/avr_isp/parts.py b/decoders/avr_isp/parts.py
index b9747f8..8e437b9 100644
--- a/decoders/avr_isp/parts.py
+++ b/decoders/avr_isp/parts.py
@@ -40,4 +40,3 @@ part = {
     (0x01, 0x02): 'Device locked',
     # TODO: Lots more entries.
 }
-
diff --git a/decoders/avr_isp/pd.py b/decoders/avr_isp/pd.py
index a6b9c80..16e3d70 100644
--- a/decoders/avr_isp/pd.py
+++ b/decoders/avr_isp/pd.py
@@ -51,18 +51,18 @@ class Decoder(srd.Decoder):
         ('dev', 'Device', (9,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.mosi_bytes, self.miso_bytes = [], []
-        self.cmd_ss, self.cmd_es = 0, 0
+        self.ss_cmd, self.es_cmd = 0, 0
         self.xx, self.yy, self.zz, self.mm = 0, 0, 0, 0
-        self.device_ss = None
+        self.ss_device = None
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def putx(self, data):
-        self.put(self.cmd_ss, self.cmd_es, self.out_ann, data)
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
 
     def handle_cmd_programming_enable(self, cmd, ret):
         # Programming enable.
@@ -99,7 +99,7 @@ class Decoder(srd.Decoder):
 
         # Store for later.
         self.mm = cmd[3]
-        self.device_ss = self.cmd_ss
+        self.ss_device = self.ss_cmd
 
         # Sanity check on reply.
         if ret[1] != 0x30 or ret[2] != cmd[1] or ret[0] != self.yy:
@@ -112,7 +112,7 @@ class Decoder(srd.Decoder):
 
         p = part[(self.part_fam_flash_size, self.part_number)]
         data = [9, ['Device: Atmel %s' % p]]
-        self.put(self.device_ss, self.cmd_es, self.out_ann, data)
+        self.put(self.ss_device, self.es_cmd, self.out_ann, data)
 
         # Sanity check on reply.
         if ret[1] != 0x30 or ret[2] != self.xx or ret[0] != self.mm:
@@ -192,7 +192,7 @@ class Decoder(srd.Decoder):
         self.ss, self.es = ss, es
 
         if len(self.mosi_bytes) == 0:
-            self.cmd_ss = ss
+            self.ss_cmd = ss
 
         # Append new bytes.
         self.mosi_bytes.append(mosi)
@@ -202,10 +202,9 @@ class Decoder(srd.Decoder):
         if len(self.mosi_bytes) < 4:
             return
 
-        self.cmd_es = es
+        self.es_cmd = es
 
         self.handle_command(self.mosi_bytes, self.miso_bytes)
 
         self.mosi_bytes = []
         self.miso_bytes = []
-
diff --git a/decoders/avr_pdi/__init__.py b/decoders/avr_pdi/__init__.py
new file mode 100644
index 0000000..ebe647b
--- /dev/null
+++ b/decoders/avr_pdi/__init__.py
@@ -0,0 +1,41 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Gerhard Sittig <gerhard.sittig at gmx.net>
+##
+## 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, see <http://www.gnu.org/licenses/>.
+##
+
+'''
+PDI (Program and Debug Interface) is an Atmel proprietary interface for
+external programming and on-chip debugging of the device. See the Atmel
+Application Note AVR1612 "PDI programming driver" and the "Program and
+Debug Interface" section in the Xmega A manual for details.
+
+The protocol uses two pins: the RESET pin and one dedicated DATA pin.
+The RESET pin provides a clock, the DATA pin communicates serial frames
+with a start bit, eight data bits, an even parity bit, and two stop bits.
+Data communication is bidirectional and half duplex, the device will
+provide response data after reception of a respective request.
+
+Protocol frames communicate opcodes and their arguments, which provides
+random and sequential access to the device's address space. By accessing
+the registers of internal peripherals, especially the NVM controller,
+it's possible to identify the device, read from and write to several
+kinds of memory (signature rows, fuses and lock bits, internal flash and
+EEPROM, memory mapped peripherals), and to control execution of software
+on the device.
+'''
+
+from .pd import Decoder
diff --git a/decoders/avr_pdi/pd.py b/decoders/avr_pdi/pd.py
new file mode 100644
index 0000000..1568fdf
--- /dev/null
+++ b/decoders/avr_pdi/pd.py
@@ -0,0 +1,586 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2011-2014 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Gerhard Sittig <gerhard.sittig at gmx.net>
+##
+## 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, see <http://www.gnu.org/licenses/>.
+##
+
+# Note the implementation details:
+#
+# Although the Atmel literature suggests (does not explicitly mandate,
+# but shows in diagrams) that two stop bits are used in the protocol,
+# the decoder loses synchronization with ATxmega generated responses
+# when it expects more than one stop bit. Since the chip's hardware is
+# fixed, this is not an implementation error in some programmer software.
+# Since this is a protocol decoder which does not participate in the
+# communication (does not actively send data), we can read the data
+# stream with one stop bit, and transparently keep working when two
+# are used.
+#
+# Annotations in the UART fields level differ from Atmel literature.
+# Wrong parity bits are referred to as "parity error". Low stop bits are
+# referred to as "frame error".
+#
+# The PDI component in the device starts disabled. Enabling PDI
+# communication is done by raising DATA and clocking RESET with a
+# minimum frequency. PDI communication automatically gets disabled when
+# RESET "is inactive" for a certain period of time. The specific timing
+# conditions are rather fuzzy in the literature (phrased weakly), and
+# are device dependent (refer to the minumum RESET pulse width). This
+# protocol decoder implementation internally prepares for but currently
+# does not support these enable and disable phases. On the one hand it
+# avoids excess external dependencies or wrong results for legal input
+# data. On the other hand the decoder works when input streams start in
+# the middle of an established connection.
+#
+# Communication peers detect physical collisions. The decoder can't.
+# Upon collisions, a peer will cease any subsequent transmission, until
+# a BREAK is seen. Synchronization can get enforced by sending two BREAK
+# conditions. The first will cause a collision, the second will re-enable
+# the peer. The decoder has no concept of physical collisions. It stops
+# the interpretation of instructions when BREAK is seen, and assumes
+# that a new instruction will start after BREAK.
+#
+# This protocol decoder only supports PDI communication over UART frames.
+# It lacks support for PDI over JTAG. This would require separation into
+# multiple protocol decoder layers (UART physical, JTAG physical, PDI
+# instructions, optionally device support on top of PDI. There is some
+# more potential for future extensions:
+# - The JTAG physical has dedicated TX and RX directions. This decoder
+#   only picks up communicated bytes but does not check which "line"
+#   they are communicated on (not applicable to half duplex UART).
+# - PDI over JTAG uses "special frame error" conditions to communicate
+#   additional symbols: BREAK (0xBB with parity 1), DELAY (0xDB with
+#   parity 1), and EMPTY (0xEB with parity 1).
+# - Another "device support" layer might interpret device specific
+#   timings, and might map addresses used in memory access operations
+#   to component names, or even register names and bit fields(?). It's
+#   quite deep a rabbithole though...
+
+import sigrokdecode as srd
+from collections import namedtuple
+
+class Ann:
+    '''Annotation and binary output classes.'''
+    (
+        BIT, START, DATA, PARITY_OK, PARITY_ERR,
+        STOP_OK, STOP_ERR, BREAK,
+        OPCODE, DATA_PROG, DATA_DEV, PDI_BREAK,
+        ENABLE, DISABLE, COMMAND,
+    ) = range(15)
+    (
+        BIN_BYTES,
+    ) = range(1)
+
+Bit = namedtuple('Bit', 'val ss es')
+
+class PDI:
+    '''PDI protocol instruction opcodes, and operand formats.'''
+    (
+        OP_LDS, OP_LD, OP_STS, OP_ST,
+        OP_LDCS, OP_REPEAT, OP_STCS, OP_KEY,
+    ) = range(8)
+    pointer_format_nice = [
+        '*(ptr)',
+        '*(ptr++)',
+        'ptr',
+        'ptr++ (rsv)',
+    ]
+    pointer_format_terse = [
+        '*p',
+        '*p++',
+        'p',
+        '(rsv)',
+    ]
+    ctrl_reg_name = {
+        0: 'status',
+        1: 'reset',
+        2: 'ctrl',
+    }
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'avr_pdi'
+    name = 'AVR PDI'
+    longname = 'Atmel Program and Debug Interface'
+    desc = 'Atmel proprietary interface for the ATxmega MCU.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['pdi']
+    channels = (
+        {'id': 'reset', 'name': 'RESET', 'desc': 'RESET / PDI_CLK'},
+        {'id': 'data', 'name': 'DATA', 'desc': 'PDI_DATA'},
+    )
+    annotations = (
+        ('uart-bit', 'UART bit'),
+        ('start-bit', 'Start bit'),
+        ('data-bit', 'Data bit'),
+        ('parity-ok', 'Parity OK bit'),
+        ('parity-err', 'Parity error bit'),
+        ('stop-ok', 'Stop OK bit'),
+        ('stop-err', 'Stop error bit'),
+        ('break', 'BREAK condition'),
+        ('opcode', 'Instruction opcode'),
+        ('data-prog', 'Programmer data'),
+        ('data-dev', 'Device data'),
+        ('pdi-break', 'BREAK at PDI level'),
+        ('enable', 'Enable PDI'),
+        ('disable', 'Disable PDI'),
+        ('cmd-data', 'PDI command with data'),
+    )
+    annotation_rows = (
+        ('uart_bits', 'UART bits', (Ann.BIT,)),
+        ('uart_fields', 'UART fields', (Ann.START, Ann.DATA, Ann.PARITY_OK,
+            Ann.PARITY_ERR, Ann.STOP_OK, Ann.STOP_ERR, Ann.BREAK)),
+        ('pdi_fields', 'PDI fields', (Ann.OPCODE, Ann.DATA_PROG, Ann.DATA_DEV,
+            Ann.PDI_BREAK)),
+        ('pdi_cmds', 'PDI Cmds', (Ann.ENABLE, Ann.DISABLE, Ann.COMMAND)),
+    )
+    binary = (
+        ('bytes', 'PDI protocol bytes'),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        # Detect input changes and clock edges.
+        self.prev_pins = None
+        self.prev_clock = None
+        self.clear_state()
+
+    def clear_state(self):
+        # Track bit times and bit values.
+        self.ss_last_fall = None
+        self.data_sample = None
+        self.ss_curr_fall = None
+        # Collect UART frame bits into byte values.
+        self.bits = []
+        self.zero_count = 0
+        self.zero_ss = None
+        self.break_ss = None
+        self.break_es = None
+        self.clear_insn()
+
+    def clear_insn(self):
+        # Collect instructions and their arguments,
+        # properties of the current instructions.
+        self.insn_rep_count = 0
+        self.insn_opcode = None
+        self.insn_wr_counts = []
+        self.insn_rd_counts = []
+        # Accumulation of data items as bytes pass by.
+        self.insn_dat_bytes = []
+        self.insn_dat_count = 0
+        self.insn_ss_data = None
+        # Next layer "commands", instructions plus operands.
+        self.cmd_ss = None
+        self.cmd_insn_parts_nice = []
+        self.cmd_insn_parts_terse = []
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+
+    def put_ann_bit(self, bit_nr, ann_idx):
+        b = self.bits[bit_nr]
+        self.put(b.ss, b.es, self.out_ann, [ann_idx, [str(b.val)]])
+
+    def put_ann_data(self, bit_nr, ann_data):
+        b = self.bits[bit_nr]
+        self.put(b.ss, b.es, self.out_ann, ann_data)
+
+    def put_ann_row_val(self, ss, es, row, value):
+        self.put(ss, es, self.out_ann, [row, value])
+
+    def put_bin_bytes(self, ss, es, row, value):
+        self.put(ss, es, self.out_binary, [row, value])
+
+    def handle_byte(self, ss, es, byteval):
+        '''Handle a byte at the PDI protocol layer.'''
+
+        # Handle BREAK conditions, which will abort any
+        # potentially currently executing instruction.
+        is_break = byteval is None
+        if is_break:
+            self.cmd_insn_parts_nice.append('BREAK')
+            self.cmd_insn_parts_terse.append('BRK')
+            self.insn_rep_count = 0
+            # Will FALLTHROUGH to "end of instruction" below.
+
+        # Decode instruction opcodes and argument sizes
+        # from the first byte of a transaction.
+        if self.insn_opcode is None and not is_break:
+            opcode = (byteval & 0xe0) >> 5
+            arg30 = byteval & 0x0f
+            arg32 = (byteval & 0x0c) >> 2
+            arg10 = byteval & 0x03
+            self.insn_opcode = opcode
+            self.cmd_ss = ss
+            mnemonics = None
+            if opcode == PDI.OP_LDS:
+                # LDS: load data, direct addressing.
+                # Writes an address, reads a data item.
+                width_addr = arg32 + 1
+                width_data = arg10 + 1
+                self.insn_wr_counts = [width_addr]
+                self.insn_rd_counts = [width_data]
+                mnemonics = [
+                    'Insn: LDS a{:d}, m{:d}'.format(width_addr, width_data),
+                    'LDS a{:d}, m{:d}'.format(width_addr, width_data), 'LDS',
+                ]
+                self.cmd_insn_parts_nice = ['LDS']
+                self.cmd_insn_parts_terse = ['LDS']
+            elif opcode == PDI.OP_LD:
+                # LD: load data, indirect addressing.
+                # Reads a data item, with optional repeat.
+                ptr_txt = PDI.pointer_format_nice[arg32]
+                ptr_txt_terse = PDI.pointer_format_terse[arg32]
+                width_data = arg10 + 1
+                self.insn_wr_counts = []
+                self.insn_rd_counts = [width_data]
+                if self.insn_rep_count:
+                    self.insn_rd_counts.extend(self.insn_rep_count * [width_data])
+                    self.insn_rep_count = 0
+                mnemonics = [
+                    'Insn: LD {:s} m{:d}'.format(ptr_txt, width_data),
+                    'LD {:s} m{:d}'.format(ptr_txt, width_data), 'LD',
+                ]
+                self.cmd_insn_parts_nice = ['LD', ptr_txt]
+                self.cmd_insn_parts_terse = ['LD', ptr_txt_terse]
+            elif opcode == PDI.OP_STS:
+                # STS: store data, direct addressing.
+                # Writes an address, writes a data item.
+                width_addr = arg32 + 1
+                width_data = arg10 + 1
+                self.insn_wr_counts = [width_addr, width_data]
+                self.insn_rd_counts = []
+                mnemonics = [
+                    'Insn: STS a{:d}, i{:d}'.format(width_addr, width_data),
+                    'STS a{:d}, i{:d}'.format(width_addr, width_data), 'STS',
+                ]
+                self.cmd_insn_parts_nice = ['STS']
+                self.cmd_insn_parts_terse = ['STS']
+            elif opcode == PDI.OP_ST:
+                # ST: store data, indirect addressing.
+                # Writes a data item, with optional repeat.
+                ptr_txt = PDI.pointer_format_nice[arg32]
+                ptr_txt_terse = PDI.pointer_format_terse[arg32]
+                width_data = arg10 + 1
+                self.insn_wr_counts = [width_data]
+                self.insn_rd_counts = []
+                if self.insn_rep_count:
+                    self.insn_wr_counts.extend(self.insn_rep_count * [width_data])
+                    self.insn_rep_count = 0
+                mnemonics = [
+                    'Insn: ST {:s} i{:d}'.format(ptr_txt, width_data),
+                    'ST {:s} i{:d}'.format(ptr_txt, width_data), 'ST',
+                ]
+                self.cmd_insn_parts_nice = ['ST', ptr_txt]
+                self.cmd_insn_parts_terse = ['ST', ptr_txt_terse]
+            elif opcode == PDI.OP_LDCS:
+                # LDCS: load control/status.
+                # Loads exactly one byte.
+                reg_num = arg30
+                reg_txt = PDI.ctrl_reg_name.get(reg_num, 'r{:d}'.format(reg_num))
+                reg_txt_terse = '{:d}'.format(reg_num)
+                self.insn_wr_counts = []
+                self.insn_rd_counts = [1]
+                mnemonics = [
+                    'Insn: LDCS {:s}, m1'.format(reg_txt),
+                    'LDCS {:s}, m1'.format(reg_txt), 'LDCS',
+                ]
+                self.cmd_insn_parts_nice = ['LDCS', reg_txt]
+                self.cmd_insn_parts_terse = ['LDCS', reg_txt_terse]
+            elif opcode == PDI.OP_STCS:
+                # STCS: store control/status.
+                # Writes exactly one byte.
+                reg_num = arg30
+                reg_txt = PDI.ctrl_reg_name.get(reg_num, 'r{:d}'.format(reg_num))
+                reg_txt_terse = '{:d}'.format(reg_num)
+                self.insn_wr_counts = [1]
+                self.insn_rd_counts = []
+                mnemonics = [
+                    'Insn: STCS {:s}, i1'.format(reg_txt),
+                    'STCS {:s}, i1'.format(reg_txt), 'STCS',
+                ]
+                self.cmd_insn_parts_nice = ['STCS', reg_txt]
+                self.cmd_insn_parts_terse = ['STCS', reg_txt_terse]
+            elif opcode == PDI.OP_REPEAT:
+                # REPEAT: sets repeat count for the next instruction.
+                # Reads repeat count from following bytes.
+                width_data = arg10 + 1
+                self.insn_wr_counts = [width_data]
+                self.insn_rd_counts = []
+                mnemonics = [
+                    'Insn: REPEAT i{:d}'.format(width_data),
+                    'REPEAT i{:d}'.format(width_data), 'REP',
+                ]
+                self.cmd_insn_parts_nice = ['REPEAT']
+                self.cmd_insn_parts_terse = ['REP']
+            elif opcode == PDI.OP_KEY:
+                # KEY: set activation key (enables PDIBUS mmap access).
+                # Writes a sequence of 8 bytes, fixed length.
+                width_data = 8
+                self.insn_wr_counts = [width_data]
+                self.insn_rd_counts = []
+                mnemonics = [
+                    'Insn: KEY i{:d}'.format(width_data),
+                    'KEY i{:d}'.format(width_data), 'KEY',
+                ]
+                self.cmd_insn_parts_nice = ['KEY']
+                self.cmd_insn_parts_terse = ['KEY']
+
+            # Emit an annotation for the instruction opcode.
+            self.put_ann_row_val(ss, es, Ann.OPCODE, mnemonics)
+
+            # Prepare to write/read operands/data bytes.
+            self.insn_dat_bytes = []
+            if self.insn_wr_counts:
+                self.insn_dat_count = self.insn_wr_counts[0]
+                return
+            if self.insn_rd_counts:
+                self.insn_dat_count = self.insn_rd_counts[0]
+                return
+            # FALLTHROUGH.
+            # When there are no operands or data bytes to read,
+            # then fall through to the end of the instruction
+            # handling below (which emits annotations).
+
+        # Read bytes which carry operands (addresses, immediates)
+        # or data values for memory access.
+        if self.insn_dat_count and not is_break:
+
+            # Accumulate received bytes until another multi byte
+            # data item is complete.
+            if not self.insn_dat_bytes:
+                self.insn_ss_data = ss
+            self.insn_dat_bytes.append(byteval)
+            self.insn_dat_count -= 1
+            if self.insn_dat_count:
+                return
+
+            # Determine the data item's duration and direction,
+            # "consume" its length spec (to simplify later steps).
+            data_ss = self.insn_ss_data
+            data_es = es
+            if self.insn_wr_counts:
+                data_ann = Ann.DATA_PROG
+                data_width = self.insn_wr_counts.pop(0)
+            elif self.insn_rd_counts:
+                data_ann = Ann.DATA_DEV
+                data_width = self.insn_rd_counts.pop(0)
+
+            # PDI communicates multi-byte data items in little endian
+            # order. Get a nice textual representation of the number,
+            # wide and narrow for several zoom levels.
+            self.insn_dat_bytes.reverse()
+            data_txt_digits = ''.join(['{:02x}'.format(b) for b in self.insn_dat_bytes])
+            data_txt_hex = '0x' + data_txt_digits
+            data_txt_prefix = 'Data: ' + data_txt_hex
+            data_txts = [data_txt_prefix, data_txt_hex, data_txt_digits]
+            self.insn_dat_bytes = []
+
+            # Emit an annotation for the data value.
+            self.put_ann_row_val(data_ss, data_es, data_ann, data_txts)
+
+            # Collect detailled information which describes the whole
+            # command when combined (for a next layer annotation,
+            # spanning the complete command).
+            self.cmd_insn_parts_nice.append(data_txt_hex)
+            self.cmd_insn_parts_terse.append(data_txt_digits)
+
+            # Send out write data first until exhausted,
+            # then drain expected read data.
+            if self.insn_wr_counts:
+                self.insn_dat_count = self.insn_wr_counts[0]
+                return
+            if self.insn_rd_counts:
+                self.insn_dat_count = self.insn_rd_counts[0]
+                return
+
+            # FALLTHROUGH.
+            # When all operands and data bytes were seen,
+            # terminate the inspection of the instruction.
+
+        # Postprocess the instruction after its operands were seen.
+        cmd_es = es
+        cmd_txt_nice = ' '.join(self.cmd_insn_parts_nice)
+        cmd_txt_terse = ' '.join(self.cmd_insn_parts_terse)
+        cmd_txts = [cmd_txt_nice, cmd_txt_terse]
+        self.put_ann_row_val(self.cmd_ss, cmd_es, Ann.COMMAND, cmd_txts)
+        if self.insn_opcode == PDI.OP_REPEAT and not is_break:
+            # The last communicated data item is the repeat
+            # count for the next instruction (i.e. it will
+            # execute N+1 times when "REPEAT N" is specified).
+            count = int(self.cmd_insn_parts_nice[-1], 0)
+            self.insn_rep_count = count
+
+        # Have the state for instruction decoding cleared, but make sure
+        # to carry over REPEAT count specs between instructions. They
+        # start out as zero, will be setup by REPEAT instructions, need
+        # to get passed to the instruction which follows REPEAT. The
+        # instruction which sees a non-zero repeat count which will
+        # consume the counter and drop it to zero, then the counter
+        # remains at zero until the next REPEAT instruction.
+        save_rep_count = self.insn_rep_count
+        self.clear_insn()
+        self.insn_rep_count = save_rep_count
+
+    def handle_bits(self, ss, es, bitval):
+        '''Handle a bit at the UART layer.'''
+
+        # Concentrate annotation literals here for easier maintenance.
+        ann_class_text = {
+            Ann.START: ['Start bit', 'Start', 'S'],
+            Ann.PARITY_OK: ['Parity OK', 'Par OK', 'P'],
+            Ann.PARITY_ERR: ['Parity error', 'Par ERR', 'PE'],
+            Ann.STOP_OK: ['Stop bit', 'Stop', 'T'],
+            Ann.STOP_ERR: ['Stop bit error', 'Stop ERR', 'TE'],
+            Ann.BREAK: ['Break condition', 'BREAK', 'BRK'],
+        }
+        def put_uart_field(bitpos, annclass):
+            self.put_ann_data(bitpos, [annclass, ann_class_text[annclass]])
+
+        # The number of bits which form one UART frame. Note that
+        # the decoder operates with only one stop bit.
+        frame_bitcount = 1 + 8 + 1 + 1
+
+        # Detect adjacent runs of all-zero bits. This is meant
+        # to cope when BREAK conditions appear at any arbitrary
+        # position, it need not be "aligned" to an UART frame.
+        if bitval == 1:
+            self.zero_count = 0
+        elif bitval == 0:
+            if not self.zero_count:
+                self.zero_ss = ss
+            self.zero_count += 1
+            if self.zero_count == frame_bitcount:
+                self.break_ss = self.zero_ss
+
+        # BREAK conditions are _at_minimum_ the length of a UART frame, but
+        # can span an arbitrary number of bit times. Track the "end sample"
+        # value of the last low bit we have seen, and emit the annotation only
+        # after the line went idle (high) again. Pass BREAK to the upper layer
+        # as well. When the line is low, BREAK still is pending. When the line
+        # is high, the current bit cannot be START, thus return from here.
+        if self.break_ss is not None:
+            if bitval == '0':
+                self.break_es = es
+                return
+            self.put(self.break_ss, self.break_es, self.out_ann,
+                 [Ann.BREAK, ann_class_text[Ann.BREAK]])
+            self.handle_byte(self.break_ss, self.break_es, None)
+            self.break_ss = None
+            self.break_es = None
+            self.bits = []
+            return
+
+        # Ignore high bits when waiting for START.
+        if not self.bits and bitval == 1:
+            return
+
+        # Store individual bits and their start/end sample numbers,
+        # until a complete frame was received.
+        self.bits.append(Bit(bitval, ss, es))
+        if len(self.bits) < frame_bitcount:
+            return
+
+        # Get individual fields of the UART frame.
+        bits_num = sum([b.val << pos for pos, b in enumerate(self.bits)])
+        if False:
+            # This logic could detect BREAK conditions which are aligned to
+            # UART frames. Which was obsoleted by the above detection at
+            # arbitrary positions. The code still can be useful to detect
+            # "other kinds of frame errors" which carry valid symbols for
+            # upper layers (the Atmel literature suggests "break", "delay",
+            # and "empty" symbols when PDI is communicated over different
+            # physical layers).
+            if bits_num == 0: # BREAK
+                self.break_ss = self.bits[0].ss
+                self.break_es = es
+                self.bits = []
+                return
+        start_bit = bits_num & 0x01; bits_num >>= 1
+        data_val = bits_num & 0xff; bits_num >>= 8
+        data_text = '{:02x}'.format(data_val)
+        parity_bit = bits_num & 0x01; bits_num >>= 1
+        stop_bit = bits_num & 0x01; bits_num >>= 1
+
+        # Check for frame errors. START _must_ have been low
+        # according to the above accumulation logic.
+        parity_ok = (bin(data_val).count('1') + parity_bit) % 2 == 0
+        stop_ok = stop_bit == 1
+        valid_frame = parity_ok and stop_ok
+
+        # Emit annotations.
+        for idx in range(frame_bitcount):
+            self.put_ann_bit(idx, Ann.BIT)
+        put_uart_field(0, Ann.START)
+        self.put(self.bits[1].ss, self.bits[8].es, self.out_ann,
+             [Ann.DATA, ['Data: ' + data_text, 'D: ' + data_text, data_text]])
+        put_uart_field(9, Ann.PARITY_OK if parity_ok else Ann.PARITY_ERR)
+        put_uart_field(10, Ann.STOP_OK if stop_ok else Ann.STOP_ERR)
+
+        # Emit binary data stream. Have bytes interpreted at higher layers.
+        if valid_frame:
+            byte_ss, byte_es = self.bits[0].ss, self.bits[-1].es
+            self.put_bin_bytes(byte_ss, byte_es, Ann.BIN_BYTES, bytes([data_val]))
+            self.handle_byte(byte_ss, byte_es, data_val)
+
+        # Reset internal state for the next frame.
+        self.bits = []
+
+    def find_clk_edge(self, samplenum, clock_pin, data_pin):
+        # Ignore the sample if the clock pin has not changed.
+        if clock_pin == self.prev_clock:
+            return
+        self.prev_clock = clock_pin
+
+        # Sample the data line on rising clock edges. Always, for TX and for
+        # RX bytes alike.
+        if clock_pin == 1:
+            self.data_sample = data_pin
+            return
+
+        # Falling clock edges are boundaries for bit slots. Inspect previously
+        # sampled bits on falling clock edges, when the start and end sample
+        # numbers were determined. Only inspect bit slots of known clock
+        # periods (avoid interpreting the DATA line when the "enabled" state
+        # has not yet been determined).
+        self.ss_last_fall = self.ss_curr_fall
+        self.ss_curr_fall = samplenum
+        if self.ss_last_fall is None:
+            return
+
+        # Have the past bit slot processed.
+        bit_ss, bit_es = self.ss_last_fall, self.ss_curr_fall
+        bit_val = self.data_sample
+        self.handle_bits(bit_ss, bit_es, bit_val)
+
+    def decode(self, ss, es, data):
+        for samplenum, pins in data:
+
+            # Ignore identical samples.
+            if self.prev_pins == pins:
+                continue
+            self.prev_pins = pins
+
+            # Have DATA processed at appropriate clock edges.
+            clock_pin, data_pin = pins[0], pins[1]
+            self.find_clk_edge(samplenum, clock_pin, data_pin)
diff --git a/decoders/can/__init__.py b/decoders/can/__init__.py
index 38731c2..60dc85f 100644
--- a/decoders/can/__init__.py
+++ b/decoders/can/__init__.py
@@ -27,5 +27,4 @@ the digital output side of a CAN transceiver IC such as the Microchip
 MCP-2515DM-BM).
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/can/pd.py b/decoders/can/pd.py
index bf38b7f..c92877b 100644
--- a/decoders/can/pd.py
+++ b/decoders/can/pd.py
@@ -20,6 +20,9 @@
 
 import sigrokdecode as srd
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'can'
@@ -54,9 +57,14 @@ class Decoder(srd.Decoder):
         ('ack-delimiter', 'ACK delimiter'),
         ('stuff-bit', 'Stuff bit'),
         ('warnings', 'Human-readable warnings'),
+        ('bit', 'Bit'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (15, 17)),
+        ('fields', 'Fields', tuple(range(15)) + (16,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.reset_variables()
 
@@ -112,8 +120,6 @@ class Decoder(srd.Decoder):
             return False
 
         # Stuff bit. Keep it in self.rawbits, but drop it from self.bits.
-        self.putx([15, ['Stuff bit: %d' % self.rawbits[-1],
-                        'SB: %d' % self.rawbits[-1], 'SB']])
         self.bits.pop() # Drop last bit.
         return True
 
@@ -302,14 +308,13 @@ class Decoder(srd.Decoder):
         # Get the index of the current CAN frame bit (without stuff bits).
         bitnum = len(self.bits) - 1
 
-        # For debugging.
-        # self.putx([0, ['Bit %d (CAN bit %d): %d' % \
-        #           (self.curbit, bitnum, can_rx)]])
-
         # If this is a stuff bit, remove it from self.bits and ignore it.
         if self.is_stuff_bit():
+            self.putx([15, [str(can_rx)]])
             self.curbit += 1 # Increase self.curbit (bitnum is not affected).
             return
+        else:
+            self.putx([17, [str(can_rx)]])
 
         # Bit 0: Start of frame (SOF) bit
         if bitnum == 0:
@@ -358,8 +363,8 @@ class Decoder(srd.Decoder):
         self.curbit += 1
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
             (can_rx,) = pins
@@ -376,6 +381,3 @@ class Decoder(srd.Decoder):
                 if not self.reached_bit(self.curbit):
                     continue
                 self.handle_bit(can_rx)
-            else:
-                raise Exception("Invalid state: %s" % self.state)
-
diff --git a/decoders/tlc5620/__init__.py b/decoders/common/__init__.py
similarity index 85%
copy from decoders/tlc5620/__init__.py
copy to decoders/common/__init__.py
index c615760..c597431 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/common/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Uwe Hermann <uwe at hermann-uwe.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
@@ -18,9 +18,3 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-'''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
-'''
-
-from .pd import *
-
diff --git a/decoders/tlc5620/__init__.py b/decoders/common/plugtrx/__init__.py
similarity index 62%
copy from decoders/tlc5620/__init__.py
copy to decoders/common/plugtrx/__init__.py
index c615760..8dd0822 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/common/plugtrx/__init__.py
@@ -1,11 +1,11 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Bert Vermeulen <bert at biot.com>
 ##
 ## 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
+## the Free Software Foundation; either version 3 of the License, or
 ## (at your option) any later version.
 ##
 ## This program is distributed in the hope that it will be useful,
@@ -14,13 +14,7 @@
 ## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
 ##
 
-'''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
-'''
-
-from .pd import *
-
+from .mod import *
diff --git a/decoders/common/plugtrx/mod.py b/decoders/common/plugtrx/mod.py
new file mode 100644
index 0000000..3d1b66d
--- /dev/null
+++ b/decoders/common/plugtrx/mod.py
@@ -0,0 +1,192 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Bert Vermeulen <bert at biot.com>
+##
+## 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 3 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, see <http://www.gnu.org/licenses/>.
+##
+
+# This module contains definitions for use by pluggable network adapters,
+# such as SFP, XFP etc.
+
+MODULE_ID = {
+    0x01: 'GBIC',
+    0x02: 'Integrated module/connector',
+    0x03: 'SFP',
+    0x04: '300-pin XBI',
+    0x05: 'XENPAK',
+    0x06: 'XFP',
+    0x07: 'XFF',
+    0x08: 'XFP-E',
+    0x09: 'XPAK',
+    0x0a: 'X2',
+}
+
+ALARM_THRESHOLDS = {
+    0:  'Temp high alarm',
+    2:  'Temp low alarm',
+    4:  'Temp high warning',
+    6:  'Temp low warning',
+    16: 'Bias high alarm',
+    18: 'Bias low alarm',
+    20: 'Bias high warning',
+    22: 'Bias low warning',
+    24: 'TX power high alarm',
+    26: 'TX power low alarm',
+    28: 'TX power high warning',
+    30: 'TX power low warning',
+    32: 'RX power high alarm',
+    34: 'RX power low alarm',
+    36: 'RX power high warning',
+    38: 'RX power low warning',
+    40: 'AUX 1 high alarm',
+    42: 'AUX 1 low alarm',
+    44: 'AUX 1 high warning',
+    46: 'AUX 1 low warning',
+    48: 'AUX 2 high alarm',
+    50: 'AUX 2 low alarm',
+    52: 'AUX 2 high warning',
+    54: 'AUX 2 low warning',
+}
+
+AD_READOUTS = {
+    0:  'Module temperature',
+    4:  'TX bias current',
+    6:  'Measured TX output power',
+    8:  'Measured RX input power',
+    10: 'AUX 1 measurement',
+    12: 'AUX 2 measurement',
+}
+
+GCS_BITS = [
+    'TX disable',
+    'Soft TX disable',
+    'MOD_NR',
+    'P_Down',
+    'Soft P_Down',
+    'Interrupt',
+    'RX_LOS',
+    'Data_Not_Ready',
+    'TX_NR',
+    'TX_Fault',
+    'TX_CDR not locked',
+    'RX_NR',
+    'RX_CDR not locked',
+]
+
+CONNECTOR = {
+    0x01:   'SC',
+    0x02:   'Fibre Channel style 1 copper',
+    0x03:   'Fibre Channel style 2 copper',
+    0x04:   'BNC/TNC',
+    0x05:   'Fibre Channel coax',
+    0x06:   'FiberJack',
+    0x07:   'LC',
+    0x08:   'MT-RJ',
+    0x09:   'MU',
+    0x0a:   'SG',
+    0x0b:   'Optical pigtail',
+    0x20:   'HSSDC II',
+    0x21:   'Copper pigtail',
+}
+
+TRANSCEIVER = [
+    # 10GB Ethernet
+    ['10GBASE-SR', '10GBASE-LR', '10GBASE-ER', '10GBASE-LRM', '10GBASE-SW',
+        '10GBASE-LW',   '10GBASE-EW'],
+    # 10GB Fibre Channel
+    ['1200-MX-SN-I', '1200-SM-LL-L', 'Extended Reach 1550 nm',
+        'Intermediate reach 1300 nm FP'],
+    # 10GB Copper
+    [],
+    # 10GB low speed
+    ['1000BASE-SX / 1xFC MMF', '1000BASE-LX / 1xFC SMF', '2xFC MMF',
+        '2xFC SMF', 'OC48-SR', 'OC48-IR', 'OC48-LR'],
+    # 10GB SONET/SDH interconnect
+    ['I-64.1r', 'I-64.1', 'I-64.2r', 'I-64.2', 'I-64.3', 'I-64.5'],
+    # 10GB SONET/SDH short haul
+    ['S-64.1', 'S-64.2a', 'S-64.2b', 'S-64.3a', 'S-64.3b', 'S-64.5a', 'S-64.5b'],
+    # 10GB SONET/SDH long haul
+    ['L-64.1', 'L-64.2a', 'L-64.2b', 'L-64.2c', 'L-64.3', 'G.959.1 P1L1-2D2'],
+    # 10GB SONET/SDH very long haul
+    ['V-64.2a', 'V-64.2b', 'V-64.3'],
+]
+
+SERIAL_ENCODING = [
+    '64B/66B',
+    '8B/10B',
+    'SONET scrambled',
+    'NRZ',
+    'RZ',
+]
+
+XMIT_TECH = [
+    '850 nm VCSEL',
+    '1310 nm VCSEL',
+    '1550 nm VCSEL',
+    '1310 nm FP',
+    '1310 nm DFB',
+    '1550 nm DFB',
+    '1310 nm EML'
+    '1550 nm EML'
+    'copper',
+]
+
+CDR = [
+    '9.95Gb/s',
+    '10.3Gb/s',
+    '10.5Gb/s',
+    '10.7Gb/s',
+    '11.1Gb/s',
+    '(unknown)',
+    'lineside loopback mode',
+    'XFI loopback mode',
+]
+
+DEVICE_TECH = [
+    ['no wavelength control', 'sctive wavelength control'],
+    ['uncooled transmitter device', 'cooled transmitter'],
+    ['PIN detector', 'APD detector'],
+    ['transmitter not tunable', 'transmitter tunable'],
+]
+
+ENHANCED_OPTS = [
+    'VPS',
+    'soft TX_DISABLE',
+    'soft P_Down',
+    'VPS LV regulator mode',
+    'VPS bypassed regulator mode',
+    'active FEC control',
+    'wavelength tunability',
+    'CMU',
+]
+
+AUX_TYPES = [
+    'not implemented',
+    'APD bias voltage',
+    '(unknown)',
+    'TEC current',
+    'laser temperature',
+    'laser wavelength',
+    '5V supply voltage',
+    '3.3V supply voltage',
+    '1.8V supply voltage',
+    '-5.2V supply voltage',
+    '5V supply current',
+    '(unknown)',
+    '(unknown)',
+    '3.3V supply current',
+    '1.8V supply current',
+    '-5.2V supply current',
+]
diff --git a/decoders/tlc5620/__init__.py b/decoders/common/sdcard/__init__.py
similarity index 85%
copy from decoders/tlc5620/__init__.py
copy to decoders/common/sdcard/__init__.py
index c615760..cf09d9d 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/common/sdcard/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2014 Uwe Hermann <uwe at hermann-uwe.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
@@ -18,9 +18,4 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-'''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
-'''
-
-from .pd import *
-
+from .mod import *
diff --git a/decoders/common/sdcard/mod.py b/decoders/common/sdcard/mod.py
new file mode 100644
index 0000000..f553cf1
--- /dev/null
+++ b/decoders/common/sdcard/mod.py
@@ -0,0 +1,186 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2012-2014 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+# Normal commands (CMD)
+# Unlisted items are 'Reserved' as per SD spec. The 'Unknown' items don't
+# seem to be mentioned in the spec, but aren't marked as reserved either.
+cmd_names = {
+    0:  'GO_IDLE_STATE',
+    1:  'SEND_OP_COND', # Reserved in SD mode
+    2:  'ALL_SEND_CID',
+    3:  'SEND_RELATIVE_ADDR',
+    4:  'SET_DSR',
+    5:  'IO_SEND_OP_COND', # SDIO-only
+    6:  'SWITCH_FUNC', # New since spec 1.10
+    7:  'SELECT/DESELECT_CARD',
+    8:  'SEND_IF_COND',
+    9:  'SEND_CSD',
+    10: 'SEND_CID',
+    11: 'VOLTAGE_SWITCH',
+    12: 'STOP_TRANSMISSION',
+    13: 'SEND_STATUS',
+    # 14: Reserved
+    15: 'GO_INACTIVE_STATE',
+    16: 'SET_BLOCKLEN',
+    17: 'READ_SINGLE_BLOCK',
+    18: 'READ_MULTIPLE_BLOCK',
+    19: 'SEND_TUNING_BLOCK',
+    20: 'SPEED_CLASS_CONTROL',
+    # 21-22: Reserved
+    23: 'SET_BLOCK_COUNT',
+    24: 'WRITE_BLOCK',
+    25: 'WRITE_MULTIPLE_BLOCK',
+    26: 'Reserved for manufacturer',
+    27: 'PROGRAM_CSD',
+    28: 'SET_WRITE_PROT',
+    29: 'CLR_WRITE_PROT',
+    30: 'SEND_WRITE_PROT',
+    # 31: Reserved
+    32: 'ERASE_WR_BLK_START', # SPI mode: ERASE_WR_BLK_START_ADDR
+    33: 'ERASE_WR_BLK_END', # SPI mode: ERASE_WR_BLK_END_ADDR
+    34: 'Reserved for CMD6', # New since spec 1.10
+    35: 'Reserved for CMD6', # New since spec 1.10
+    36: 'Reserved for CMD6', # New since spec 1.10
+    37: 'Reserved for CMD6', # New since spec 1.10
+    38: 'ERASE',
+    # 39: Reserved
+    40: 'Reserved for security specification',
+    # 41: Reserved
+    42: 'LOCK_UNLOCK',
+    # 43-49: Reserved
+    50: 'Reserved for CMD6', # New since spec 1.10
+    # 51: Reserved
+    52: 'IO_RW_DIRECT', # SDIO-only
+    53: 'IO_RW_EXTENDED', # SDIO-only
+    54: 'Unknown',
+    55: 'APP_CMD',
+    56: 'GEN_CMD',
+    57: 'Reserved for CMD6', # New since spec 1.10
+    58: 'READ_OCR', # Reserved in SD mode
+    59: 'CRC_ON_OFF', # Reserved in SD mode
+    60: 'Reserved for manufacturer',
+    61: 'Reserved for manufacturer',
+    62: 'Reserved for manufacturer',
+    63: 'Reserved for manufacturer',
+}
+
+# Application-specific commands (ACMD)
+# Unlisted items are 'Reserved' as per SD spec. The 'Unknown' items don't
+# seem to be mentioned in the spec, but aren't marked as reserved either.
+acmd_names = {
+    # 1-5: Reserved
+    6:  'SET_BUS_WIDTH',
+    # 7-12: Reserved
+    13: 'SD_STATUS',
+    14: 'Reserved for Security Application',
+    15: 'Reserved for Security Application',
+    16: 'Reserved for Security Application',
+    # 17: Reserved
+    18: 'Reserved for SD security applications',
+    # 19-21: Reserved
+    22: 'SEND_NUM_WR_BLOCKS',
+    23: 'SET_WR_BLK_ERASE_COUNT',
+    # 24: Reserved
+    25: 'Reserved for SD security applications',
+    26: 'Reserved for SD security applications',
+    27: 'Reserved for security specification',
+    28: 'Reserved for security specification',
+    # 29: Reserved
+    30: 'Reserved for security specification',
+    31: 'Reserved for security specification',
+    32: 'Reserved for security specification',
+    33: 'Reserved for security specification',
+    34: 'Reserved for security specification',
+    35: 'Reserved for security specification',
+    # 36-37: Reserved
+    38: 'Reserved for SD security applications',
+    # 39-40: Reserved
+    41: 'SD_SEND_OP_COND',
+    42: 'SET_CLR_CARD_DETECT',
+    43: 'Reserved for SD security applications',
+    44: 'Reserved for SD security applications',
+    45: 'Reserved for SD security applications',
+    46: 'Reserved for SD security applications',
+    47: 'Reserved for SD security applications',
+    48: 'Reserved for SD security applications',
+    49: 'Reserved for SD security applications',
+    50: 'Unknown',
+    51: 'SEND_SCR',
+    52: 'Reserved for security specification',
+    53: 'Reserved for security specification',
+    54: 'Reserved for security specification',
+    55: 'Non-existant', # Doesn't exist (equivalent to CMD55)
+    56: 'Reserved for security specification',
+    57: 'Reserved for security specification',
+    58: 'Reserved for security specification',
+    59: 'Reserved for security specification',
+    60: 'Unknown',
+    61: 'Unknown',
+    62: 'Unknown',
+    63: 'Unknown',
+}
+
+accepted_voltages = {
+    0b0001: '2.7-3.6V',
+    0b0010: 'reserved for low voltage range',
+    0b0100: 'reserved',
+    0b1000: 'reserved',
+    # All other values: "not defined".
+}
+
+card_status = {
+    0:  'Reserved for manufacturer test mode',
+    1:  'Reserved for manufacturer test mode',
+    2:  'Reserved for application specific commands',
+    3:  'AKE_SEQ_ERROR',
+    4:  'Reserved for SDIO card',
+    5:  'APP_CMD',
+    6:  'Unknown',
+    7:  'Unknown',
+    8:  'READY_FOR_DATA',
+    9:  'CURRENT_STATE', # CURRENT_STATE is a 4-bit value (decimal: 0..15).
+    10: 'CURRENT_STATE',
+    11: 'CURRENT_STATE',
+    12: 'CURRENT_STATE',
+    13: 'ERASE_RESET',
+    14: 'CARD_ECC_DISABLED',
+    15: 'WP_ERASE_SKIP',
+    16: 'CSD_OVERWRITE',
+    17: 'Reserved for DEFERRED_RESPONSE', # See eSD addendum
+    18: 'Reserved',
+    19: 'ERROR',
+    20: 'CC_ERROR',
+    21: 'CARD_ECC_FAILED',
+    22: 'ILLEGAL_COMMAND',
+    23: 'COM_CRC_ERROR',
+    24: 'LOCK_UNLOCK_FAILED',
+    25: 'CARD_IS_LOCKED',
+    26: 'WP_VIOLATION',
+    27: 'ERASE_PARAM',
+    28: 'ERASE_SEQ_ERROR',
+    29: 'BLOCK_LEN_ERROR',
+    30: 'ADDRESS_ERROR',
+    31: 'OUT_OF_RANGE',
+}
+
+sd_status = {
+    # 311:0: Reserved for manufacturer
+    # 391:312: Reserved
+}
diff --git a/decoders/tlc5620/__init__.py b/decoders/common/srdhelper/__init__.py
similarity index 85%
copy from decoders/tlc5620/__init__.py
copy to decoders/common/srdhelper/__init__.py
index c615760..cf09d9d 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/common/srdhelper/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2014 Uwe Hermann <uwe at hermann-uwe.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
@@ -18,9 +18,4 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-'''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
-'''
-
-from .pd import *
-
+from .mod import *
diff --git a/decoders/ir_nec/__init__.py b/decoders/common/srdhelper/mod.py
similarity index 81%
copy from decoders/ir_nec/__init__.py
copy to decoders/common/srdhelper/mod.py
index 84bf428..e65ab17 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/common/srdhelper/mod.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2012-2014 Uwe Hermann <uwe at hermann-uwe.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
@@ -18,9 +18,6 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-'''
-NEC is a pulse-distance based infrared remote control protocol.
-'''
-
-from .pd import *
-
+# Return the specified BCD number (max. 8 bits) as integer.
+def bcd2int(b):
+    return (b & 0x0f) + ((b >> 4) * 10)
diff --git a/decoders/dcf77/__init__.py b/decoders/dcf77/__init__.py
index 04805c2..8423028 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/dcf77/__init__.py
@@ -26,5 +26,4 @@ Details:
 http://en.wikipedia.org/wiki/DCF77
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/dcf77/pd.py b/decoders/dcf77/pd.py
index fc97a1d..0f1d3d1 100644
--- a/decoders/dcf77/pd.py
+++ b/decoders/dcf77/pd.py
@@ -20,10 +20,10 @@
 
 import sigrokdecode as srd
 import calendar
+from common.srdhelper import bcd2int
 
-# Return the specified BCD number (max. 8 bits) as integer.
-def bcd2int(b):
-    return (b & 0x0f) + ((b >> 4) * 10)
+class SamplerateError(Exception):
+    pass
 
 class Decoder(srd.Decoder):
     api_version = 2
@@ -65,7 +65,7 @@ class Decoder(srd.Decoder):
         ('warnings', 'Warnings', (19,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.state = 'WAIT FOR RISING EDGE'
         self.oldpins = None
@@ -239,14 +239,14 @@ class Decoder(srd.Decoder):
             # Even parity over date bits (36-58): DCF77 bit 58.
             parity = self.datebits.count(1)
             s = 'OK' if ((parity % 2) == 0) else 'INVALID!'
-            self.putx([16, ['Date parity: %s' % s, 'DP: %s' %s]])
+            self.putx([16, ['Date parity: %s' % s, 'DP: %s' % s]])
             self.datebits = []
         else:
             raise Exception('Invalid DCF77 bit: %d' % c)
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
             # Ignore identical samples early on (for performance reasons).
@@ -310,8 +310,4 @@ class Decoder(srd.Decoder):
 
                 self.state = 'WAIT FOR RISING EDGE'
 
-            else:
-                raise Exception('Invalid state: %s' % self.state)
-
             self.oldval = val
-
diff --git a/decoders/ir_nec/__init__.py b/decoders/dmx512/__init__.py
similarity index 80%
copy from decoders/ir_nec/__init__.py
copy to decoders/dmx512/__init__.py
index 84bf428..9761dd5 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/dmx512/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2016 Fabian J. Stumpf <sigrok at fabianstumpf.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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+DMX512 (Digital MultipleX 512) is a protocol based on RS485, used to control
+professional lighting fixtures.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/dmx512/pd.py b/decoders/dmx512/pd.py
new file mode 100644
index 0000000..e684b13
--- /dev/null
+++ b/decoders/dmx512/pd.py
@@ -0,0 +1,170 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Fabian J. Stumpf <sigrok at fabianstumpf.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'dmx512'
+    name = 'DMX512'
+    longname = 'Digital MultipleX 512'
+    desc = 'Professional lighting control protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['dmx512']
+    channels = (
+        {'id': 'dmx', 'name': 'DMX data', 'desc': 'Any DMX data line'},
+    )
+    annotations = (
+        ('bit', 'Bit'),
+        ('break', 'Break'),
+        ('mab', 'Mark after break'),
+        ('startbit', 'Start bit'),
+        ('stopbits', 'Stop bit'),
+        ('startcode', 'Start code'),
+        ('channel', 'Channel'),
+        ('interframe', 'Interframe'),
+        ('interpacket', 'Interpacket'),
+        ('data', 'Data'),
+        ('error', 'Error'),
+    )
+    annotation_rows = (
+        ('name', 'Logical', (1, 2, 5, 6, 7, 8)),
+        ('data', 'Data', (9,)),
+        ('bits', 'Bits', (0, 3, 4)),
+        ('errors', 'Errors', (10,)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.sample_usec = None
+        self.samplenum = -1
+        self.run_start = -1
+        self.run_bit = 0
+        self.state = 'FIND BREAK'
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+            self.sample_usec = 1 / value * 1000000
+            self.skip_per_bit = int(4 / self.sample_usec)
+
+    def putr(self, data):
+        self.put(self.run_start, self.samplenum, self.out_ann, data)
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, pins) in data:
+            # Seek for an interval with no state change with a length between
+            # 88 and 1000000 us (BREAK).
+            if self.state == 'FIND BREAK':
+                if self.run_bit == pins[0]:
+                    continue
+                runlen = (self.samplenum - self.run_start) * self.sample_usec
+                if runlen > 88 and runlen < 1000000:
+                    self.putr([1, ['Break']])
+                    self.bit_break = self.run_bit
+                    self.state = 'MARK MAB'
+                    self.channel = 0
+                elif runlen >= 1000000:
+                    # Error condition.
+                    self.putr([10, ['Invalid break length']])
+                self.run_bit = pins[0]
+                self.run_start = self.samplenum
+            # Directly following the BREAK is the MARK AFTER BREAK.
+            elif self.state == 'MARK MAB':
+                if self.run_bit == pins[0]:
+                    continue
+                self.putr([2, ['MAB']])
+                self.state = 'READ BYTE'
+                self.channel = 0
+                self.bit = 0
+                self.aggreg = pins[0]
+                self.run_start = self.samplenum
+            # Mark and read a single transmitted byte
+            # (start bit, 8 data bits, 2 stop bits).
+            elif self.state == 'READ BYTE':
+                self.next_sample = self.run_start + (self.bit + 1) * self.skip_per_bit
+                self.aggreg += pins[0]
+                if self.samplenum != self.next_sample:
+                    continue
+                bit_value = 0 if round(self.aggreg/self.skip_per_bit) == self.bit_break else 1
+
+                if self.bit == 0:
+                    self.byte = 0
+                    self.putr([3, ['Start bit']])
+                    if bit_value != 0:
+                        # (Possibly) invalid start bit, mark but don't fail.
+                        self.put(self.samplenum, self.samplenum,
+                                 self.out_ann, [10, ['Invalid start bit']])
+                elif self.bit >= 9:
+                    self.put(self.samplenum - self.skip_per_bit,
+                        self.samplenum, self.out_ann, [4, ['Stop bit']])
+                    if bit_value != 1:
+                        # Invalid stop bit, mark.
+                        self.put(self.samplenum, self.samplenum,
+                            self.out_ann, [10, ['Invalid stop bit']])
+                        if self.bit == 10:
+                            # On invalid 2nd stop bit, search for new break.
+                            self.run_bit = pins[0]
+                            self.state = 'FIND BREAK'
+                else:
+                    # Label and process one bit.
+                    self.put(self.samplenum - self.skip_per_bit,
+                        self.samplenum, self.out_ann, [0, [str(bit_value)]])
+                    self.byte |= bit_value << (self.bit - 1)
+
+                # Label a complete byte.
+                if self.bit == 10:
+                    if self.channel == 0:
+                        d = [5, ['Start code']]
+                    else:
+                        d = [6, ['Channel ' + str(self.channel)]]
+                    self.put(self.run_start, self.next_sample, self.out_ann, d)
+                    self.put(self.run_start + self.skip_per_bit,
+                        self.next_sample - 2 * self.skip_per_bit,
+                        self.out_ann, [9, [str(self.byte) + ' / ' + \
+                        str(hex(self.byte))]])
+                    # Continue by scanning the IFT.
+                    self.channel += 1
+                    self.run_start = self.samplenum
+                    self.run_bit = pins[0]
+                    self.state = 'MARK IFT'
+
+                self.aggreg = pins[0]
+                self.bit += 1
+            # Mark the INTERFRAME-TIME between bytes / INTERPACKET-TIME between packets.
+            elif self.state == 'MARK IFT':
+                if self.run_bit == pins[0]:
+                    continue
+                if self.channel > 512:
+                    self.putr([8, ['Interpacket']])
+                    self.state = 'FIND BREAK'
+                    self.run_bit = pins[0]
+                    self.run_start = self.samplenum
+                else:
+                    self.putr([7, ['Interframe']])
+                    self.state = 'READ BYTE'
+                    self.bit = 0
+                    self.run_start = self.samplenum
diff --git a/decoders/ds1307/__init__.py b/decoders/ds1307/__init__.py
index 5bc28c3..7166229 100644
--- a/decoders/ds1307/__init__.py
+++ b/decoders/ds1307/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'i2c' PD and decodes the Dallas DS1307
 real-time clock (RTC) specific registers and commands.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/ds1307/pd.py b/decoders/ds1307/pd.py
index 68943d4..f181fd9 100644
--- a/decoders/ds1307/pd.py
+++ b/decoders/ds1307/pd.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
-## 
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+##
+## Copyright (C) 2012-2014 Uwe Hermann <uwe at hermann-uwe.de>
 ## Copyright (C) 2013 Matt Ranostay <mranostay at gmail.com>
 ##
 ## This program is free software; you can redistribute it and/or modify
@@ -19,21 +19,38 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
+import re
 import sigrokdecode as srd
+from common.srdhelper import bcd2int
+
+days_of_week = (
+    'Sunday', 'Monday', 'Tuesday', 'Wednesday',
+    'Thursday', 'Friday', 'Saturday',
+)
+
+regs = (
+    'Seconds', 'Minutes', 'Hours', 'Day', 'Date', 'Month', 'Year',
+    'Control', 'RAM',
+)
+
+bits = (
+    'Clock halt', 'Seconds', 'Reserved', 'Minutes', '12/24 hours', 'AM/PM',
+    'Hours', 'Day', 'Date', 'Month', 'Year', 'OUT', 'SQWE', 'RS', 'RAM',
+)
+
+rates = {
+    0b00: '1Hz',
+    0b01: '4096kHz',
+    0b10: '8192kHz',
+    0b11: '32768kHz',
+}
 
-days_of_week = [
-    'Sunday',
-    'Monday',
-    'Tuesday',
-    'Wednesday',
-    'Thursday',
-    'Friday',
-    'Saturday',
-]
+DS1307_I2C_ADDRESS = 0x68
 
-# Return the specified BCD number (max. 8 bits) as integer.
-def bcd2int(b):
-    return (b & 0x0f) + ((b >> 4) * 10)
+def regs_and_bits():
+    l = [('reg-' + r.lower(), r + ' register') for r in regs]
+    l += [('bit-' + re.sub('\/| ', '-', b).lower(), b + ' bit') for b in bits]
+    return tuple(l)
 
 class Decoder(srd.Decoder):
     api_version = 2
@@ -44,11 +61,21 @@ class Decoder(srd.Decoder):
     license = 'gplv2+'
     inputs = ['i2c']
     outputs = ['ds1307']
-    annotations = (
-        ('text', 'Human-readable text'),
+    annotations =  regs_and_bits() + (
+        ('read-datetime', 'Read date/time'),
+        ('write-datetime', 'Write date/time'),
+        ('reg-read', 'Register read'),
+        ('reg-write', 'Register write'),
+        ('warnings', 'Warnings'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', tuple(range(9, 24))),
+        ('regs', 'Registers', tuple(range(9))),
+        ('date-time', 'Date/time', (24, 25, 26, 27)),
+        ('warnings', 'Warnings', (28,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.hours = -1
         self.minutes = -1
@@ -57,6 +84,7 @@ class Decoder(srd.Decoder):
         self.date = -1
         self.months = -1
         self.years = -1
+        self.bits = []
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
@@ -64,40 +92,124 @@ class Decoder(srd.Decoder):
     def putx(self, data):
         self.put(self.ss, self.es, self.out_ann, data)
 
-    def handle_reg_0x00(self, b): # Seconds
-        self.seconds = bcd2int(b & 0x7f)
-        self.putx([0, ['Seconds: %d' % self.seconds]])
+    def putd(self, bit1, bit2, data):
+        self.put(self.bits[bit1][1], self.bits[bit2][2], self.out_ann, data)
+
+    def putr(self, bit):
+        self.put(self.bits[bit][1], self.bits[bit][2], self.out_ann,
+                 [11, ['Reserved bit', 'Reserved', 'Rsvd', 'R']])
 
-    def handle_reg_0x01(self, b): # Minutes
-        self.minutes = bcd2int(b & 0x7f)
-        self.putx([0, ['Minutes: %d' % self.minutes]])
+    def handle_reg_0x00(self, b): # Seconds (0-59) / Clock halt bit
+        self.putd(7, 0, [0, ['Seconds', 'Sec', 'S']])
+        ch = 1 if (b & (1 << 7)) else 0
+        self.putd(7, 7, [9, ['Clock halt: %d' % ch, 'Clk hlt: %d' % ch,
+                        'CH: %d' % ch, 'CH']])
+        s = self.seconds = bcd2int(b & 0x7f)
+        self.putd(6, 0, [10, ['Second: %d' % s, 'Sec: %d' % s, 'S: %d' % s, 'S']])
 
-    def handle_reg_0x02(self, b): # Hours
-        self.hours = bcd2int(b & 0x3f)
-        self.putx([0, ['Hours: %d' % self.hours]])
+    def handle_reg_0x01(self, b): # Minutes (0-59)
+        self.putd(7, 0, [1, ['Minutes', 'Min', 'M']])
+        self.putr(7)
+        m = self.minutes = bcd2int(b & 0x7f)
+        self.putd(6, 0, [12, ['Minute: %d' % m, 'Min: %d' % m, 'M: %d' % m, 'M']])
 
-    def handle_reg_0x03(self, b): # Day of week
-        self.days = bcd2int(b & 0x7)
-        self.putx([0, ['Day of Week: %s' % days_of_week[self.days - 1]]])
+    def handle_reg_0x02(self, b): # Hours (1-12+AM/PM or 0-23)
+        self.putd(7, 0, [2, ['Hours', 'H']])
+        self.putr(7)
+        ampm_mode = True if (b & (1 << 6)) else False
+        if ampm_mode:
+            self.putd(6, 6, [13, ['12-hour mode', '12h mode', '12h']])
+            a = 'AM' if (b & (1 << 6)) else 'PM'
+            self.putd(5, 5, [14, [a, a[0]]])
+            h = self.hours = bcd2int(b & 0x1f)
+            self.putd(4, 0, [15, ['Hour: %d' % h, 'H: %d' % h, 'H']])
+        else:
+            self.putd(6, 6, [13, ['24-hour mode', '24h mode', '24h']])
+            h = self.hours = bcd2int(b & 0x3f)
+            self.putd(5, 0, [15, ['Hour: %d' % h, 'H: %d' % h, 'H']])
 
-    def handle_reg_0x04(self, b): # Date
-        self.date =  bcd2int(b & 0x3f)
-        self.putx([0, ['Days: %d' % self.date]])
+    def handle_reg_0x03(self, b): # Day / day of week (1-7)
+        self.putd(7, 0, [3, ['Day of week', 'Day', 'D']])
+        for i in (7, 6, 5, 4, 3):
+            self.putr(i)
+        w = self.days = bcd2int(b & 0x07)
+        ws = days_of_week[self.days - 1]
+        self.putd(2, 0, [16, ['Weekday: %s' % ws, 'WD: %s' % ws, 'WD', 'W']])
 
-    def handle_reg_0x05(self, b): # Month
-        self.months = bcd2int(b & 0x1f)
-        self.putx([0, ['Months: %d' % self.months]])
+    def handle_reg_0x04(self, b): # Date (1-31)
+        self.putd(7, 0, [4, ['Date', 'D']])
+        for i in (7, 6):
+            self.putr(i)
+        d = self.date = bcd2int(b & 0x3f)
+        self.putd(5, 0, [17, ['Date: %d' % d, 'D: %d' % d, 'D']])
 
-    def handle_reg_0x06(self, b): # Year
-        self.years = bcd2int(b & 0xff) + 2000;
-        self.putx([0, ['Years: %d' % self.years]])
+    def handle_reg_0x05(self, b): # Month (1-12)
+        self.putd(7, 0, [5, ['Month', 'Mon', 'M']])
+        for i in (7, 6, 5):
+            self.putr(i)
+        m = self.months = bcd2int(b & 0x1f)
+        self.putd(4, 0, [18, ['Month: %d' % m, 'Mon: %d' % m, 'M: %d' % m, 'M']])
+
+    def handle_reg_0x06(self, b): # Year (0-99)
+        self.putd(7, 0, [6, ['Year', 'Y']])
+        y = self.years = bcd2int(b & 0xff)
+        self.years += 2000
+        self.putd(7, 0, [19, ['Year: %d' % y, 'Y: %d' % y, 'Y']])
 
     def handle_reg_0x07(self, b): # Control Register
-        pass
+        self.putd(7, 0, [7, ['Control', 'Ctrl', 'C']])
+        for i in (6, 5, 3, 2):
+            self.putr(i)
+        o = 1 if (b & (1 << 7)) else 0
+        s = 1 if (b & (1 << 4)) else 0
+        s2 = 'en' if (b & (1 << 4)) else 'dis'
+        r = rates[b & 0x03]
+        self.putd(7, 7, [20, ['Output control: %d' % o,
+            'OUT: %d' % o, 'O: %d' % o, 'O']])
+        self.putd(4, 4, [21, ['Square wave output: %sabled' % s2,
+            'SQWE: %sabled' % s2, 'SQWE: %d' % s, 'S: %d' % s, 'S']])
+        self.putd(1, 0, [22, ['Square wave output rate: %s' % r,
+            'Square wave rate: %s' % r, 'SQW rate: %s' % r, 'Rate: %s' % r,
+            'RS: %s' % s, 'RS', 'R']])
+
+    def handle_reg_0x3f(self, b): # RAM (bytes 0x08-0x3f)
+        self.putd(7, 0, [8, ['RAM', 'R']])
+        self.putd(7, 0, [23, ['SRAM: 0x%02X' % b, '0x%02X' % b]])
+
+    def output_datetime(self, cls, rw):
+        # TODO: Handle read/write of only parts of these items.
+        d = '%s, %02d.%02d.%4d %02d:%02d:%02d' % (
+            days_of_week[self.days - 1], self.date, self.months,
+            self.years, self.hours, self.minutes, self.seconds)
+        self.put(self.ss_block, self.es, self.out_ann,
+                 [cls, ['%s date/time: %s' % (rw, d)]])
+
+    def handle_reg(self, b):
+        r = self.reg if self.reg < 8 else 0x3f
+        fn = getattr(self, 'handle_reg_0x%02x' % r)
+        fn(b)
+        # Honor address auto-increment feature of the DS1307. When the
+        # address reaches 0x3f, it will wrap around to address 0.
+        self.reg += 1
+        if self.reg > 0x3f:
+            self.reg = 0
+
+    def is_correct_chip(self, addr):
+        if addr == DS1307_I2C_ADDRESS:
+            return True
+        self.put(self.ss_block, self.es, self.out_ann,
+                 [28, ['Ignoring non-DS1307 data (slave 0x%02X)' % addr]])
+        return False
 
     def decode(self, ss, es, data):
         cmd, databyte = data
 
+        # Collect the 'BITS' packet, then return. The next packet is
+        # guaranteed to belong to these bits we just stored.
+        if cmd == 'BITS':
+            self.bits = databyte
+            return
+
         # Store the start/end samples of this I²C packet.
         self.ss, self.es = ss, es
 
@@ -107,12 +219,14 @@ class Decoder(srd.Decoder):
             if cmd != 'START':
                 return
             self.state = 'GET SLAVE ADDR'
-            self.block_start_sample = ss
+            self.ss_block = ss
         elif self.state == 'GET SLAVE ADDR':
             # Wait for an address write operation.
-            # TODO: We should only handle packets to the RTC slave (0x68).
             if cmd != 'ADDRESS WRITE':
                 return
+            if not self.is_correct_chip(databyte):
+                self.state = 'IDLE'
+                return
             self.state = 'GET REG ADDR'
         elif self.state == 'GET REG ADDR':
             # Wait for a data write (master selects the slave register).
@@ -121,49 +235,27 @@ class Decoder(srd.Decoder):
             self.reg = databyte
             self.state = 'WRITE RTC REGS'
         elif self.state == 'WRITE RTC REGS':
-            # If we see a Repeated Start here, it's probably an RTC read.
+            # If we see a Repeated Start here, it's an RTC read.
             if cmd == 'START REPEAT':
                 self.state = 'READ RTC REGS'
                 return
             # Otherwise: Get data bytes until a STOP condition occurs.
             if cmd == 'DATA WRITE':
-                handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)
-                handle_reg(databyte)
-                self.reg += 1
-                # TODO: Check for NACK!
+                self.handle_reg(databyte)
             elif cmd == 'STOP':
-                # TODO: Handle read/write of only parts of these items.
-                d = '%s, %02d.%02d.%02d %02d:%02d:%02d' % (
-                    days_of_week[self.days - 1], self.date, self.months,
-                    self.years, self.hours, self.minutes, self.seconds)
-                self.put(self.block_start_sample, es, self.out_ann,
-                         [0, ['Written date/time: %s' % d]])
+                self.output_datetime(25, 'Written')
                 self.state = 'IDLE'
-            else:
-                pass # TODO
         elif self.state == 'READ RTC REGS':
             # Wait for an address read operation.
-            # TODO: We should only handle packets to the RTC slave (0x68).
-            if cmd == 'ADDRESS READ':
-                self.state = 'READ RTC REGS2'
+            if cmd != 'ADDRESS READ':
+                return
+            if not self.is_correct_chip(databyte):
+                self.state = 'IDLE'
                 return
-            else:
-                pass # TODO
+            self.state = 'READ RTC REGS2'
         elif self.state == 'READ RTC REGS2':
             if cmd == 'DATA READ':
-                handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)
-                handle_reg(databyte)
-                self.reg += 1
-                # TODO: Check for NACK!
+                self.handle_reg(databyte)
             elif cmd == 'STOP':
-                d = '%s, %02d.%02d.%02d %02d:%02d:%02d' % (
-                    days_of_week[self.days - 1], self.date, self.months,
-                    self.years, self.hours, self.minutes, self.seconds)
-                self.put(self.block_start_sample, es, self.out_ann,
-                         [0, ['Read date/time: %s' % d]])
+                self.output_datetime(24, 'Read')
                 self.state = 'IDLE'
-            else:
-                pass # TODO?
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/edid/__init__.py b/decoders/edid/__init__.py
index 8683006..de544d3 100644
--- a/decoders/edid/__init__.py
+++ b/decoders/edid/__init__.py
@@ -36,5 +36,4 @@ More information on EDID is available here:
  https://en.wikipedia.org/wiki/Extended_display_identification_data
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/edid/pd.py b/decoders/edid/pd.py
index 8af10ae..389fbda 100644
--- a/decoders/edid/pd.py
+++ b/decoders/edid/pd.py
@@ -85,8 +85,12 @@ class Decoder(srd.Decoder):
         ('fields', 'EDID structure fields'),
         ('sections', 'EDID structure sections'),
     )
+    annotation_rows = (
+        ('sections', 'Sections', (1,)),
+        ('fields', 'Fields', (0,)),
+    )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = None
         # Received data items, used as an index into samplenum/data
         self.cnt = 0
@@ -109,7 +113,6 @@ class Decoder(srd.Decoder):
         self.sn.append([ss, es])
         self.cache.append(data)
         # debug
-#        self.put(ss, es, self.out_ann, [0, ['%d: [%.2x]' % (self.cnt, data)]])
 
         if self.state is None:
             # Wait for the EDID header
@@ -120,24 +123,43 @@ class Decoder(srd.Decoder):
                     self.cache = self.cache[-8:]
                     self.cnt = 8
                     self.state = 'edid'
-                    self.put(ss, es, self.out_ann, [0, ['EDID header']])
+                    self.put(self.sn[0][0], es, self.out_ann,
+                            [ANN_SECTIONS, ['Header']])
+                    self.put(self.sn[0][0], es, self.out_ann,
+                            [ANN_FIELDS, ['Header pattern']])
         elif self.state == 'edid':
             if self.cnt == OFF_VERSION:
                 self.decode_vid(-10)
                 self.decode_pid(-8)
                 self.decode_serial(-6)
                 self.decode_mfrdate(-2)
+                self.put(self.sn[OFF_VENDOR][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['Vendor/product']])
             elif self.cnt == OFF_BASIC:
-                version = 'EDID version: %d.%d' % (self.cache[-2], self.cache[-1])
-                self.put(ss, es, self.out_ann, [0, [version]])
+                self.put(self.sn[OFF_VERSION][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['EDID Version']])
+                self.put(self.sn[OFF_VERSION][0], self.sn[OFF_VERSION][1],
+                        self.out_ann, [ANN_FIELDS,
+                            ['Version %d' % self.cache[-2]]])
+                self.put(self.sn[OFF_VERSION+1][0], self.sn[OFF_VERSION+1][1],
+                        self.out_ann, [ANN_FIELDS,
+                            ['Revision %d' % self.cache[-1]]])
             elif self.cnt == OFF_CHROM:
+                self.put(self.sn[OFF_BASIC][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['Basic display']])
                 self.decode_basicdisplay(-5)
             elif self.cnt == OFF_EST_TIMING:
+                self.put(self.sn[OFF_CHROM][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['Color characteristics']])
                 self.decode_chromaticity(-10)
             elif self.cnt == OFF_STD_TIMING:
+                self.put(self.sn[OFF_EST_TIMING][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['Established timings']])
                 self.decode_est_timing(-3)
             elif self.cnt == OFF_DET_TIMING:
-                self.decode_std_timing(-16)
+                self.put(self.sn[OFF_STD_TIMING][0], es, self.out_ann,
+                        [ANN_SECTIONS, ['Standard timings']])
+                self.decode_std_timing(self.cnt - 16)
             elif self.cnt == OFF_NUM_EXT:
                 self.decode_descriptors(-72)
             elif self.cnt == OFF_CHECKSUM:
@@ -311,7 +333,7 @@ class Decoder(srd.Decoder):
                     modestr += est_modes[i] + ', '
         if modestr:
             self.ann_field(offset, offset+2,
-                           'Supported establised modes: %s' % modestr[:-2])
+                           'Supported established modes: %s' % modestr[:-2])
 
     def decode_std_timing(self, offset):
         modestr = ''
@@ -326,8 +348,8 @@ class Decoder(srd.Decoder):
             refresh = (self.cache[offset+i+1] & 0x3f) + 60
             modestr += '%dx%d@%dHz, ' % (x, y, refresh)
         if modestr:
-            self.ann_field(offset, offset+2,
-                           'Supported standard modes: %s' % modestr[:-2])
+            self.ann_field(offset, offset + 15,
+                    'Supported standard modes: %s' % modestr[:-2])
 
     def decode_detailed_timing(self, offset):
         if offset == -72 and self.have_preferred_timing:
@@ -336,7 +358,7 @@ class Decoder(srd.Decoder):
         else:
             section = 'Detailed'
         section += ' timing descriptor'
-        self.put(self.sn[offset][0], self.sn[offset+18][1],
+        self.put(self.sn[offset][0], self.sn[offset+17][1],
              self.out_ann, [ANN_SECTIONS, [section]])
 
         pixclock = float((self.cache[offset+1] << 8) + self.cache[offset]) / 100
@@ -346,38 +368,36 @@ class Decoder(srd.Decoder):
         self.ann_field(offset+2, offset+4, 'Horizontal active: %d' % horiz_active)
 
         horiz_blank = ((self.cache[offset+4] & 0x0f) << 8) + self.cache[offset+3]
-        self.ann_field(offset+3, offset+4, 'Horizontal blanking: %d' % horiz_blank)
+        self.ann_field(offset+2, offset+4, 'Horizontal blanking: %d' % horiz_blank)
 
         vert_active = ((self.cache[offset+7] & 0xf0) << 4) + self.cache[offset+5]
         self.ann_field(offset+5, offset+7, 'Vertical active: %d' % vert_active)
 
         vert_blank = ((self.cache[offset+7] & 0x0f) << 8) + self.cache[offset+6]
-        self.ann_field(offset+6, offset+7, 'Vertical blanking: %d' % vert_blank)
+        self.ann_field(offset+5, offset+7, 'Vertical blanking: %d' % vert_blank)
 
         horiz_sync_off = ((self.cache[offset+11] & 0xc0) << 2) + self.cache[offset+8]
         self.ann_field(offset+8, offset+11, 'Horizontal sync offset: %d' % horiz_sync_off)
 
         horiz_sync_pw = ((self.cache[offset+11] & 0x30) << 4) + self.cache[offset+9]
-        self.ann_field(offset+9, offset+11, 'Horizontal sync pulse width: %d' % horiz_sync_pw)
+        self.ann_field(offset+8, offset+11, 'Horizontal sync pulse width: %d' % horiz_sync_pw)
 
         vert_sync_off = ((self.cache[offset+11] & 0x0c) << 2) \
                     + ((self.cache[offset+10] & 0xf0) >> 4)
-        self.ann_field(offset+10, offset+11, 'Vertical sync offset: %d' % vert_sync_off)
+        self.ann_field(offset+8, offset+11, 'Vertical sync offset: %d' % vert_sync_off)
 
         vert_sync_pw = ((self.cache[offset+11] & 0x03) << 4) \
                     + (self.cache[offset+10] & 0x0f)
-        self.ann_field(offset+10, offset+11, 'Vertical sync pulse width: %d' % vert_sync_pw)
+        self.ann_field(offset+8, offset+11, 'Vertical sync pulse width: %d' % vert_sync_pw)
 
         horiz_size = ((self.cache[offset+14] & 0xf0) << 4) + self.cache[offset+12]
         vert_size = ((self.cache[offset+14] & 0x0f) << 8) + self.cache[offset+13]
         self.ann_field(offset+12, offset+14, 'Physical size: %dx%dmm' % (horiz_size, vert_size))
 
         horiz_border = self.cache[offset+15]
-        if horiz_border:
-            self.ann_field(offset+15, offset+15, 'Horizontal border: %d pixels' % horiz_border)
+        self.ann_field(offset+15, offset+15, 'Horizontal border: %d pixels' % horiz_border)
         vert_border = self.cache[offset+16]
-        if vert_border:
-            self.ann_field(offset+16, offset+16, 'Vertical border: %d lines' % vert_border)
+        self.ann_field(offset+16, offset+16, 'Vertical border: %d lines' % vert_border)
 
         features = 'Flags: '
         if self.cache[offset+17] & 0x80:
@@ -418,16 +438,22 @@ class Decoder(srd.Decoder):
         tag = self.cache[offset+3]
         if tag == 0xff:
             # Monitor serial number
+            self.put(self.sn[offset][0], self.sn[offset+17][1], self.out_ann,
+                     [ANN_SECTIONS, ['Serial number']])
             text = bytes(self.cache[offset+5:][:13]).decode(encoding='cp437', errors='replace')
-            self.ann_field(offset, offset+17, 'Serial number: %s' % text.strip())
+            self.ann_field(offset, offset+17, text.strip())
         elif tag == 0xfe:
             # Text
+            self.put(self.sn[offset][0], self.sn[offset+17][1], self.out_ann,
+                     [ANN_SECTIONS, ['Text']])
             text = bytes(self.cache[offset+5:][:13]).decode(encoding='cp437', errors='replace')
-            self.ann_field(offset, offset+17, 'Info: %s' % text.strip())
+            self.ann_field(offset, offset+17, text.strip())
         elif tag == 0xfc:
             # Monitor name
+            self.put(self.sn[offset][0], self.sn[offset+17][1], self.out_ann,
+                     [ANN_SECTIONS, ['Monitor name']])
             text = bytes(self.cache[offset+5:][:13]).decode(encoding='cp437', errors='replace')
-            self.ann_field(offset, offset+17, 'Model name: %s' % text.strip())
+            self.ann_field(offset, offset+17, text.strip())
         elif tag == 0xfd:
             # Monitor range limits
             self.put(self.sn[offset][0], self.sn[offset+17][1], self.out_ann,
@@ -465,4 +491,3 @@ class Decoder(srd.Decoder):
             else:
                 if self.cache[i+2] == 0 or self.cache[i+4] == 0:
                     self.decode_descriptor(i)
-
diff --git a/decoders/ir_rc5/__init__.py b/decoders/eeprom24xx/__init__.py
similarity index 86%
copy from decoders/ir_rc5/__init__.py
copy to decoders/eeprom24xx/__init__.py
index 085082f..de19da4 100644
--- a/decoders/ir_rc5/__init__.py
+++ b/decoders/eeprom24xx/__init__.py
@@ -19,8 +19,8 @@
 ##
 
 '''
-RC-5 is a biphase/manchester based infrared remote control protocol.
+This decoder stacks on top of the 'i2c' PD and decodes the
+industry standard 24xx series serial EEPROM protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/eeprom24xx/lists.py b/decoders/eeprom24xx/lists.py
new file mode 100644
index 0000000..ff4b3ed
--- /dev/null
+++ b/decoders/eeprom24xx/lists.py
@@ -0,0 +1,171 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+#
+# Chip specific properties:
+#
+# - vendor: chip manufacturer
+# - model: chip model
+# - size: total EEPROM size (in number of bytes)
+# - page_size: page size (in number of bytes)
+# - page_wraparound: Whether writes wrap-around at page boundaries
+# - addr_bytes: number of EEPROM address bytes used
+# - addr_pins: number of address pins (A0/A1/A2) on this chip
+# - max_speed: max. supported I²C speed (in kHz)
+#
+chips = {
+    # Generic chip (128 bytes, 8 bytes page size)
+    'generic': {
+        'vendor': '',
+        'model': 'Generic',
+        'size': 128,
+        'page_size': 8,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+
+    # Microchip
+    'microchip_24aa65': {
+        'vendor': 'Microchip',
+        'model': '24AA65',
+        'size': 8 * 1024,
+        'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
+        'page_wraparound': True,
+        'addr_bytes': 2,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+    'microchip_24lc65': {
+        'vendor': 'Microchip',
+        'model': '24LC65',
+        'size': 8 * 1024,
+        'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
+        'page_wraparound': True,
+        'addr_bytes': 2,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+    'microchip_24c65': {
+        'vendor': 'Microchip',
+        'model': '24C65',
+        'size': 8 * 1024,
+        'page_size': 64, # Actually 8, but there are 8 pages of "input cache"
+        'page_wraparound': True,
+        'addr_bytes': 2,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+    'microchip_24aa64': {
+        'vendor': 'Microchip',
+        'model': '24AA64',
+        'size': 8 * 1024,
+        'page_size': 32,
+        'page_wraparound': True,
+        'addr_bytes': 2,
+        'addr_pins': 3,
+        'max_speed': 400, # 100 for VCC < 2.5V
+    },
+    'microchip_24lc64': {
+        'vendor': 'Microchip',
+        'model': '24LC64',
+        'size': 8 * 1024,
+        'page_size': 32,
+        'page_wraparound': True,
+        'addr_bytes': 2,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+    'microchip_24aa02uid': {
+        'vendor': 'Microchip',
+        'model': '24AA02UID',
+        'size': 256,
+        'page_size': 8,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 0, # Pins A0, A1, A2 not used
+        'max_speed': 400,
+    },
+    'microchip_24aa025uid': {
+        'vendor': 'Microchip',
+        'model': '24AA025UID',
+        'size': 256,
+        'page_size': 16,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 3,
+        'max_speed': 400,
+    },
+    'microchip_24aa025uid_sot23': {
+        'vendor': 'Microchip',
+        'model': '24AA025UID (SOT-23)',
+        'size': 256,
+        'page_size': 16,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 2, # SOT-23 package: A2 not available
+        'max_speed': 400,
+    },
+
+    # Siemens
+    'siemens_slx_24c01': {
+        'vendor': 'Siemens',
+        'model': 'SLx 24C01',
+        'size': 128,
+        'page_size': 8,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 0, # Pins A0, A1, A2 are not connected (NC)
+        'max_speed': 400,
+    },
+    'siemens_slx_24c02': {
+        'vendor': 'Siemens',
+        'model': 'SLx 24C02',
+        'size': 256,
+        'page_size': 8,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 0, # Pins A0, A1, A2 are not connected (NC)
+        'max_speed': 400,
+    },
+
+    # ST
+    'st_m24c01': {
+        'vendor': 'ST',
+        'model': 'M24C01',
+        'size': 128,
+        'page_size': 16,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 3, # Called E0, E1, E2 on this chip.
+        'max_speed': 400,
+    },
+    'st_m24c02': {
+        'vendor': 'ST',
+        'model': 'M24C02',
+        'size': 256,
+        'page_size': 16,
+        'page_wraparound': True,
+        'addr_bytes': 1,
+        'addr_pins': 3, # Called E0, E1, E2 on this chip.
+        'max_speed': 400,
+    },
+}
diff --git a/decoders/eeprom24xx/pd.py b/decoders/eeprom24xx/pd.py
new file mode 100644
index 0000000..73269a6
--- /dev/null
+++ b/decoders/eeprom24xx/pd.py
@@ -0,0 +1,430 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from .lists import *
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'eeprom24xx'
+    name = '24xx EEPROM'
+    longname = '24xx I²C EEPROM'
+    desc = '24xx series I²C EEPROM protocol.'
+    license = 'gplv2+'
+    inputs = ['i2c']
+    outputs = ['eeprom24xx']
+    options = (
+        {'id': 'chip', 'desc': 'Chip', 'default': 'generic',
+            'values': tuple(chips.keys())},
+        {'id': 'addr_counter', 'desc': 'Initial address counter value',
+            'default': 0},
+    )
+    annotations = (
+        # Warnings
+        ('warnings', 'Warnings'),
+        # Bits/bytes
+        ('control-code', 'Control code'),
+        ('address-pin', 'Address pin (A0/A1/A2)'),
+        ('rw-bit', 'Read/write bit'),
+        ('word-addr-byte', 'Word address byte'),
+        ('data-byte', 'Data byte'),
+        # Fields
+        ('control-word', 'Control word'),
+        ('word-addr', 'Word address'),
+        ('data', 'Data'),
+        # Operations
+        ('byte-write', 'Byte write'),
+        ('page-write', 'Page write'),
+        ('cur-addr-read', 'Current address read'),
+        ('random-read', 'Random read'),
+        ('seq-random-read', 'Sequential random read'),
+        ('seq-cur-addr-read', 'Sequential current address read'),
+        ('ack-polling', 'Acknowledge polling'),
+        ('set-bank-addr', 'Set bank address'), # SBA. Only 34AA04.
+        ('read-bank-addr', 'Read bank address'), # RBA. Only 34AA04.
+        ('set-wp', 'Set write protection'), # SWP
+        ('clear-all-wp', 'Clear all write protection'), # CWP
+        ('read-wp', 'Read write protection status'), # RPS
+    )
+    annotation_rows = (
+        ('bits-bytes', 'Bits/bytes', (1, 2, 3, 4, 5)),
+        ('fields', 'Fields', (6, 7, 8)),
+        ('ops', 'Operations', tuple(range(9, 21))),
+        ('warnings', 'Warnings', (0,)),
+    )
+    binary = (
+        ('binary', 'Binary'),
+    )
+
+    def __init__(self):
+        self.reset()
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+        self.chip = chips[self.options['chip']]
+        self.addr_counter = self.options['addr_counter']
+
+    def putb(self, data):
+        self.put(self.ss_block, self.es_block, self.out_ann, data)
+
+    def putbin(self, data):
+        self.put(self.ss_block, self.es_block, self.out_binary, data)
+
+    def putbits(self, bit1, bit2, bits, data):
+        self.put(bits[bit1][1], bits[bit2][2], self.out_ann, data)
+
+    def reset(self):
+        self.state = 'WAIT FOR START'
+        self.packets = []
+        self.bytebuf = []
+        self.is_cur_addr_read = False
+        self.is_random_access_read = False
+        self.is_seq_random_read = False
+        self.is_byte_write = False
+        self.is_page_write = False
+
+    def packet_append(self):
+        self.packets.append([self.ss, self.es, self.cmd, self.databyte, self.bits])
+        if self.cmd in ('DATA READ', 'DATA WRITE'):
+            self.bytebuf.append(self.databyte)
+
+    def hexbytes(self, idx):
+        return ' '.join(['%02X' % b for b in self.bytebuf[idx:]])
+
+    def put_control_word(self, bits):
+        s = ''.join(['%d' % b[0] for b in reversed(bits[4:])])
+        self.putbits(7, 4, bits, [1, ['Control code bits: ' + s,
+            'Control code: ' + s, 'Ctrl code: ' + s, 'Ctrl code', 'Ctrl', 'C']])
+        for i in reversed(range(self.chip['addr_pins'])):
+            self.putbits(i + 1, i + 1, bits,
+                [2, ['Address bit %d: %d' % (i, bits[i + 1][0]),
+                     'Addr bit %d' % i, 'A%d' % i, 'A']])
+        s1 = 'read' if bits[0][0] == 1 else 'write'
+        s2 = 'R' if bits[0][0] == 1 else 'W'
+        self.putbits(0, 0, bits, [3, ['R/W bit: ' + s1, 'R/W', 'RW', s2]])
+        self.putbits(7, 0, bits, [6, ['Control word', 'Control', 'CW', 'C']])
+
+    def put_word_addr(self, p):
+        if self.chip['addr_bytes'] == 1:
+            a = p[1][3]
+            self.put(p[1][0], p[1][1], self.out_ann,
+                [4, ['Word address byte: %02X' % a, 'Word addr byte: %02X' % a,
+                     'Addr: %02X' % a, 'A: %02X' % a, '%02X' % a]])
+            self.put(p[1][0], p[1][1], self.out_ann, [7, ['Word address',
+                     'Word addr', 'Addr', 'A']])
+            self.addr_counter = a
+        else:
+            a = p[1][3]
+            self.put(p[1][0], p[1][1], self.out_ann,
+                [4, ['Word address high byte: %02X' % a,
+                     'Word addr high byte: %02X' % a,
+                     'Addr high: %02X' % a, 'AH: %02X' % a, '%02X' % a]])
+            a = p[2][3]
+            self.put(p[2][0], p[2][1], self.out_ann,
+                [4, ['Word address low byte: %02X' % a,
+                     'Word addr low byte: %02X' % a,
+                     'Addr low: %02X' % a, 'AL: %02X' % a, '%02X' % a]])
+            self.put(p[1][0], p[2][1], self.out_ann, [7, ['Word address',
+                     'Word addr', 'Addr', 'A']])
+            self.addr_counter = (p[1][3] << 8) | p[2][3]
+
+    def put_data_byte(self, p):
+        if self.chip['addr_bytes'] == 1:
+            s = '%02X' % self.addr_counter
+        else:
+            s = '%04X' % self.addr_counter
+        self.put(p[0], p[1], self.out_ann, [5, ['Data byte %s: %02X' % \
+            (s, p[3]), 'Data byte: %02X' % p[3], \
+            'Byte: %02X' % p[3], 'DB: %02X' % p[3], '%02X' % p[3]]])
+
+    def put_data_bytes(self, idx, cls, s):
+        for p in self.packets[idx:]:
+            self.put_data_byte(p)
+            self.addr_counter += 1
+        self.put(self.packets[idx][0], self.packets[-1][1], self.out_ann,
+            [8, ['Data', 'D']])
+        a = ''.join(['%s' % c[0] for c in s.split()]).upper()
+        self.putb([cls, ['%s (%s): %s' % (s, self.addr_and_len(), \
+                  self.hexbytes(self.chip['addr_bytes'])),
+                  '%s (%s)' % (s, self.addr_and_len()), s, a, s[0]]])
+        self.putbin([0, bytes(self.bytebuf[self.chip['addr_bytes']:])])
+
+    def addr_and_len(self):
+        if self.chip['addr_bytes'] == 1:
+            a = '%02X' % self.bytebuf[0]
+        else:
+            a = '%02X%02X' % tuple(self.bytebuf[:2])
+        num_data_bytes = len(self.bytebuf) - self.chip['addr_bytes']
+        d = '%d bytes' % num_data_bytes
+        if num_data_bytes <= 1:
+            d = d[:-1]
+        return 'addr=%s, %s' % (a, d)
+
+    def decide_on_seq_or_rnd_read(self):
+        if len(self.bytebuf) < 2:
+            self.reset()
+            return
+        if len(self.bytebuf) == 2:
+            self.is_random_access_read = True
+        else:
+            self.is_seq_random_read = True
+
+    def put_operation(self):
+        idx = 1 + self.chip['addr_bytes']
+        if self.is_byte_write:
+            # Byte write: word address, one data byte.
+            self.put_word_addr(self.packets)
+            self.put_data_bytes(idx, 9, 'Byte write')
+        elif self.is_page_write:
+            # Page write: word address, two or more data bytes.
+            self.put_word_addr(self.packets)
+            intitial_addr = self.addr_counter
+            self.put_data_bytes(idx, 10, 'Page write')
+            num_bytes_to_write = len(self.packets[idx:])
+            if num_bytes_to_write > self.chip['page_size']:
+                self.putb([0, ['Warning: Wrote %d bytes but page size is '
+                               'only %d bytes!' % (num_bytes_to_write,
+                               self.chip['page_size'])]])
+            page1 = int(intitial_addr / self.chip['page_size'])
+            page2 = int((self.addr_counter - 1) / self.chip['page_size'])
+            if page1 != page2:
+                self.putb([0, ['Warning: Page write crossed page boundary '
+                               'from page %d to %d!' % (page1, page2)]])
+        elif self.is_cur_addr_read:
+            # Current address read: no word address, one data byte.
+            self.put_data_byte(self.packets[1])
+            self.put(self.packets[1][0], self.packets[-1][1], self.out_ann,
+                [8, ['Data', 'D']])
+            self.putb([11, ['Current address read: %02X' % self.bytebuf[0],
+                       'Current address read', 'Cur addr read', 'CAR', 'C']])
+            self.putbin([0, bytes([self.bytebuf[0]])])
+            self.addr_counter += 1
+        elif self.is_random_access_read:
+            # Random access read: word address, one data byte.
+            self.put_control_word(self.packets[idx][4])
+            self.put_word_addr(self.packets)
+            self.put_data_bytes(idx + 1, 12, 'Random access read')
+        elif self.is_seq_random_read:
+            # Sequential random read: word address, two or more data bytes.
+            self.put_control_word(self.packets[idx][4])
+            self.put_word_addr(self.packets)
+            self.put_data_bytes(idx + 1, 13, 'Sequential random read')
+
+    def handle_wait_for_start(self):
+        # Wait for an I²C START condition.
+        if self.cmd not in ('START', 'START REPEAT'):
+            return
+        self.ss_block = self.ss
+        self.state = 'GET CONTROL WORD'
+
+    def handle_get_control_word(self):
+        # The packet after START must be an ADDRESS READ or ADDRESS WRITE.
+        if self.cmd not in ('ADDRESS READ', 'ADDRESS WRITE'):
+            self.reset()
+            return
+        self.packet_append()
+        self.put_control_word(self.bits)
+        self.state = '%s GET ACK NACK AFTER CONTROL WORD' % self.cmd[8]
+
+    def handle_r_get_ack_nack_after_control_word(self):
+        if self.cmd == 'ACK':
+            self.state = 'R GET WORD ADDR OR BYTE'
+        elif self.cmd == 'NACK':
+            self.es_block = self.es
+            self.putb([0, ['Warning: No reply from slave!']])
+            self.reset()
+        else:
+            self.reset()
+
+    def handle_r_get_word_addr_or_byte(self):
+        if self.cmd == 'STOP':
+            self.es_block = self.es
+            self.putb([0, ['Warning: Slave replied, but master aborted!']])
+            self.reset()
+            return
+        elif self.cmd != 'DATA READ':
+            self.reset()
+            return
+        self.packet_append()
+        self.state = 'R GET ACK NACK AFTER WORD ADDR OR BYTE'
+
+    def handle_r_get_ack_nack_after_word_addr_or_byte(self):
+        if self.cmd == 'ACK':
+            self.state = 'R GET RESTART'
+        elif self.cmd == 'NACK':
+            self.is_cur_addr_read = True
+            self.state = 'GET STOP AFTER LAST BYTE'
+        else:
+            self.reset()
+
+    def handle_r_get_restart(self):
+        if self.cmd == 'RESTART':
+            self.state = 'R READ BYTE'
+        else:
+            self.reset()
+
+    def handle_r_read_byte(self):
+        if self.cmd == 'DATA READ':
+            self.packet_append()
+            self.state = 'R GET ACK NACK AFTER BYTE WAS READ'
+        else:
+            self.reset()
+
+    def handle_r_get_ack_nack_after_byte_was_read(self):
+        if self.cmd == 'ACK':
+            self.state = 'R READ BYTE'
+        elif self.cmd == 'NACK':
+            # It's either a RANDOM READ or a SEQUENTIAL READ.
+            self.state = 'GET STOP AFTER LAST BYTE'
+        else:
+            self.reset()
+
+    def handle_w_get_ack_nack_after_control_word(self):
+        if self.cmd == 'ACK':
+            self.state = 'W GET WORD ADDR'
+        elif self.cmd == 'NACK':
+            self.es_block = self.es
+            self.putb([0, ['Warning: No reply from slave!']])
+            self.reset()
+        else:
+            self.reset()
+
+    def handle_w_get_word_addr(self):
+        if self.cmd == 'STOP':
+            self.es_block = self.es
+            self.putb([0, ['Warning: Slave replied, but master aborted!']])
+            self.reset()
+            return
+        elif self.cmd != 'DATA WRITE':
+            self.reset()
+            return
+        self.packet_append()
+        self.state = 'W GET ACK AFTER WORD ADDR'
+
+    def handle_w_get_ack_after_word_addr(self):
+        if self.cmd == 'ACK':
+            self.state = 'W DETERMINE EEPROM READ OR WRITE'
+        else:
+            self.reset()
+
+    def handle_w_determine_eeprom_read_or_write(self):
+        if self.cmd == 'START REPEAT':
+            # It's either a RANDOM ACCESS READ or SEQUENTIAL RANDOM READ.
+            self.state = 'R2 GET CONTROL WORD'
+        elif self.cmd == 'DATA WRITE':
+            self.packet_append()
+            self.state = 'W GET ACK NACK AFTER BYTE WAS WRITTEN'
+        else:
+            self.reset()
+
+    def handle_w_write_byte(self):
+        if self.cmd == 'DATA WRITE':
+            self.packet_append()
+            self.state = 'W GET ACK NACK AFTER BYTE WAS WRITTEN'
+        elif self.cmd == 'STOP':
+            if len(self.bytebuf) < 2:
+                self.reset()
+                return
+            self.es_block = self.es
+            if len(self.bytebuf) == 2:
+                self.is_byte_write = True
+            else:
+                self.is_page_write = True
+            self.put_operation()
+            self.reset()
+        elif self.cmd == 'START REPEAT':
+            # It's either a RANDOM ACCESS READ or SEQUENTIAL RANDOM READ.
+            self.state = 'R2 GET CONTROL WORD'
+        else:
+            self.reset()
+
+    def handle_w_get_ack_nack_after_byte_was_written(self):
+        if self.cmd == 'ACK':
+            self.state = 'W WRITE BYTE'
+        else:
+            self.reset()
+
+    def handle_r2_get_control_word(self):
+        if self.cmd == 'ADDRESS READ':
+            self.packet_append()
+            self.state = 'R2 GET ACK AFTER ADDR READ'
+        else:
+            self.reset()
+
+    def handle_r2_get_ack_after_addr_read(self):
+        if self.cmd == 'ACK':
+            self.state = 'R2 READ BYTE'
+        else:
+            self.reset()
+
+    def handle_r2_read_byte(self):
+        if self.cmd == 'DATA READ':
+            self.packet_append()
+            self.state = 'R2 GET ACK NACK AFTER BYTE WAS READ'
+        elif self.cmd == 'STOP':
+            self.decide_on_seq_or_rnd_read()
+            self.es_block = self.es
+            self.putb([0, ['Warning: STOP expected after a NACK (not ACK)']])
+            self.put_operation()
+            self.reset()
+        else:
+            self.reset()
+
+    def handle_r2_get_ack_nack_after_byte_was_read(self):
+        if self.cmd == 'ACK':
+            self.state = 'R2 READ BYTE'
+        elif self.cmd == 'NACK':
+            self.decide_on_seq_or_rnd_read()
+            self.state = 'GET STOP AFTER LAST BYTE'
+        else:
+            self.reset()
+
+    def handle_get_stop_after_last_byte(self):
+        if self.cmd == 'STOP':
+            self.es_block = self.es
+            self.put_operation()
+            self.reset()
+        elif self.cmd == 'START REPEAT':
+            self.es_block = self.es
+            self.putb([0, ['Warning: STOP expected (not RESTART)']])
+            self.put_operation()
+            self.reset()
+            self.ss_block = self.ss
+            self.state = 'GET CONTROL WORD'
+        else:
+            self.reset()
+
+    def decode(self, ss, es, data):
+        self.cmd, self.databyte = data
+
+        # Collect the 'BITS' packet, then return. The next packet is
+        # guaranteed to belong to these bits we just stored.
+        if self.cmd == 'BITS':
+            self.bits = self.databyte
+            return
+
+        # Store the start/end samples of this I²C packet.
+        self.ss, self.es = ss, es
+
+        # State machine.
+        s = 'handle_%s' % self.state.lower().replace(' ', '_')
+        handle_state = getattr(self, s)
+        handle_state()
diff --git a/decoders/ir_nec/__init__.py b/decoders/em4100/__init__.py
similarity index 83%
copy from decoders/ir_nec/__init__.py
copy to decoders/em4100/__init__.py
index 84bf428..cff361f 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/em4100/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Benjamin Larsson <benjamin at southpole.se>
 ##
 ## 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
@@ -19,8 +19,7 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+EM4100 is a biphase/manchester/PSK based 100-150kHz RFID protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/em4100/pd.py b/decoders/em4100/pd.py
new file mode 100644
index 0000000..0768f9d
--- /dev/null
+++ b/decoders/em4100/pd.py
@@ -0,0 +1,237 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Benjamin Larsson <benjamin at southpole.se>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'em4100'
+    name = 'EM4100'
+    longname = 'RFID EM4100'
+    desc = 'EM4100 100-150kHz RFID protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['em4100']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    options = (
+        {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-high',
+            'values': ('active-low', 'active-high')},
+        {'id': 'datarate' , 'desc': 'Data rate', 'default': 64,
+            'values': (64, 32, 16)},
+#        {'id': 'coding', 'desc': 'Bit coding', 'default': 'biphase',
+#            'values': ('biphase', 'manchester', 'psk')},
+        {'id': 'coilfreq', 'desc': 'Coil frequency', 'default': 125000},
+    )
+    annotations = (
+        ('bit', 'Bit'),
+        ('header', 'Header'),
+        ('version-customer', 'Version/customer'),
+        ('data', 'Data'),
+        ('rowparity-ok', 'Row parity OK'),
+        ('rowparity-err', 'Row parity error'),
+        ('colparity-ok', 'Column parity OK'),
+        ('colparity-err', 'Column parity error'),
+        ('stopbit', 'Stop bit'),
+        ('tag', 'Tag'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0,)),
+        ('fields', 'Fields', (1, 2, 3, 4, 5, 6, 7, 8)),
+        ('tags', 'Tags', (9,)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.oldpin = None
+        self.last_samplenum = None
+        self.lastlast_samplenum = None
+        self.last_edge = 0
+        self.bit_width = 0
+        self.halfbit_limit = 0
+        self.oldpp = 0
+        self.oldpl = 0
+        self.oldsamplenum = 0
+        self.last_bit_pos = 0
+        self.ss_first = 0
+        self.first_one = 0
+        self.state = 'HEADER'
+        self.data = 0
+        self.data_bits = 0
+        self.ss_data = 0
+        self.data_parity = 0
+        self.payload_cnt = 0
+        self.data_col_parity = [0, 0, 0, 0, 0, 0]
+        self.col_parity = [0, 0, 0, 0, 0, 0]
+        self.tag = 0
+        self.all_row_parity_ok = True
+        self.col_parity_pos = []
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+        self.bit_width = (self.samplerate / self.options['coilfreq']) * self.options['datarate']
+        self.halfbit_limit = self.bit_width/2 + self.bit_width/4
+        self.polarity = 0 if self.options['polarity'] == 'active-low' else 1
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putbit(self, bit, ss, es):
+        self.put(ss, es, self.out_ann, [0, [str(bit)]])
+        if self.state == 'HEADER':
+            if bit == 1:
+                if self.first_one > 0:
+                    self.first_one += 1
+                if self.first_one == 9:
+                    self.put(self.ss_first, es, self.out_ann,
+                             [1, ['Header', 'Head', 'He', 'H']])
+                    self.first_one = 0
+                    self.state = 'PAYLOAD'
+                    return
+                if self.first_one == 0:
+                    self.first_one = 1
+                    self.ss_first = ss
+
+            if bit == 0:
+                self.first_one = 0
+            return
+
+        if self.state == 'PAYLOAD':
+            self.payload_cnt += 1
+            if self.data_bits == 0:
+                self.ss_data = ss
+                self.data = 0
+                self.data_parity = 0
+            self.data_bits += 1
+            if self.data_bits == 5:
+                s = 'Version/customer' if self.payload_cnt <= 10 else 'Data'
+                c = 2 if self.payload_cnt <= 10 else 3
+                self.put(self.ss_data, ss, self.out_ann,
+                         [c, [s + ': %X' % self.data, '%X' % self.data]])
+                s = 'OK' if self.data_parity == bit else 'ERROR'
+                c = 4 if s == 'OK' else 5
+                if s == 'ERROR':
+                    self.all_row_parity_ok = False
+                self.put(ss, es, self.out_ann,
+                         [c, ['Row parity: ' + s, 'RP: ' + s, 'RP', 'R']])
+                self.tag = (self.tag << 4) | self.data
+                self.data_bits = 0
+                if self.payload_cnt == 50:
+                    self.state = 'TRAILER'
+                    self.payload_cnt = 0
+
+            self.data_parity ^= bit
+            self.data_col_parity[self.data_bits] ^= bit
+            self.data = (self.data << 1) | bit
+            return
+
+        if self.state == 'TRAILER':
+            self.payload_cnt += 1
+            if self.data_bits == 0:
+                self.ss_data = ss
+                self.data = 0
+                self.data_parity = 0
+            self.data_bits += 1
+            self.col_parity[self.data_bits] = bit
+            self.col_parity_pos.append([ss, es])
+
+            if self.data_bits == 5:
+                self.put(ss, es, self.out_ann, [8, ['Stop bit', 'SB', 'S']])
+
+                for i in range(1, 5):
+                    s = 'OK' if self.data_col_parity[i] == \
+                                self.col_parity[i] else 'ERROR'
+                    c = 6 if s == 'OK' else 7
+                    self.put(self.col_parity_pos[i - 1][0],
+                             self.col_parity_pos[i - 1][1], self.out_ann,
+                             [c, ['Column parity %d: %s' % (i, s),
+                                  'CP%d: %s' % (i, s), 'CP%d' % i, 'C']])
+
+                # Emit an annotation for valid-looking tags.
+                all_col_parity_ok = (self.data_col_parity[1:5] == self.col_parity[1:5])
+                if all_col_parity_ok and self.all_row_parity_ok:
+                    self.put(self.ss_first, es, self.out_ann,
+                             [9, ['Tag: %010X' % self.tag, 'Tag', 'T']])
+
+                self.tag = 0
+                self.data_bits = 0
+
+                if self.payload_cnt == 5:
+                    self.state = 'HEADER'
+                    self.payload_cnt = 0
+                    self.data_col_parity = [0, 0, 0, 0, 0, 0]
+                    self.col_parity = [0, 0, 0, 0, 0, 0]
+                    self.col_parity_pos = []
+                    self.all_row_parity_ok = True
+
+    def manchester_decode(self, samplenum, pl, pp, pin):
+        bit = self.oldpin ^ self.polarity
+        if pl > self.halfbit_limit:
+            es = int(samplenum - pl/2)
+            if self.oldpl > self.halfbit_limit:
+                ss = int(self.oldsamplenum - self.oldpl/2)
+            else:
+                ss = int(self.oldsamplenum - self.oldpl)
+            self.putbit(bit, ss, es)
+            self.last_bit_pos = int(samplenum - pl/2)
+        else:
+            es = int(samplenum)
+            if self.oldpl > self.halfbit_limit:
+                ss = int(self.oldsamplenum - self.oldpl/2)
+                self.putbit(bit, ss, es)
+                self.last_bit_pos = int(samplenum)
+            else:
+                if self.last_bit_pos <= self.oldsamplenum - self.oldpl:
+                    ss = int(self.oldsamplenum - self.oldpl)
+                    self.putbit(bit, ss, es)
+                    self.last_bit_pos = int(samplenum)
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (samplenum, (pin,)) in data:
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpin == pin:
+                continue
+
+            if self.oldpin is None:
+                self.oldpin = pin
+                self.last_samplenum = samplenum
+                self.lastlast_samplenum = samplenum
+                self.last_edge = samplenum
+                self.oldpl = 0
+                self.oldpp = 0
+                self.oldsamplenum = 0
+                self.last_bit_pos = 0
+                continue
+
+            if self.oldpin != pin:
+                pl = samplenum - self.oldsamplenum
+                pp = pin
+                self.manchester_decode(samplenum, pl, pp, pin)
+                self.oldpl = pl
+                self.oldpp = pp
+                self.oldsamplenum = samplenum
+                self.oldpin = pin
diff --git a/decoders/tlc5620/__init__.py b/decoders/em4305/__init__.py
similarity index 86%
copy from decoders/tlc5620/__init__.py
copy to decoders/em4305/__init__.py
index c615760..1c1896a 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/em4305/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Benjamin Larsson <benjamin at southpole.se>
 ##
 ## 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
@@ -19,8 +19,7 @@
 ##
 
 '''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
+EM4305 is a 100-150kHz RFID protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/em4305/pd.py b/decoders/em4305/pd.py
new file mode 100644
index 0000000..73ed955
--- /dev/null
+++ b/decoders/em4305/pd.py
@@ -0,0 +1,396 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Benjamin Larsson <benjamin at southpole.se>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'em4305'
+    name = 'EM4305'
+    longname = 'RFID EM4205/EM4305'
+    desc = 'EM4205/EM4305 100-150kHz RFID protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['em4305']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    options = (
+        {'id': 'coilfreq', 'desc': 'Coil frequency', 'default': 125000},
+        {'id': 'first_field_stop', 'desc': 'First field stop min', 'default': 40},
+        {'id': 'w_gap', 'desc': 'Write gap min', 'default': 12},
+        {'id': 'w_one_max', 'desc': 'Write one max', 'default': 32},
+        {'id': 'w_zero_on_min', 'desc': 'Write zero on min', 'default': 15},
+        {'id': 'w_zero_off_max', 'desc': 'Write zero off max', 'default': 27},
+        {'id': 'em4100_decode', 'desc': 'EM4100 decode', 'default': 'on',
+            'values': ('on', 'off')},
+    )
+    annotations = (
+        ('bit_value', 'Bit value'),
+        ('first_field_stop', 'First field stop'),
+        ('write_gap', 'Write gap'),
+        ('write_mode_exit', 'Write mode exit'),
+        ('bit', 'Bit'),
+        ('opcode', 'Opcode'),
+        ('lock', 'Lock'),
+        ('data', 'Data'),
+        ('password', 'Password'),
+        ('address', 'Address'),
+        ('bitrate', 'Bitrate'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0,)),
+        ('structure', 'Structure', (1, 2, 3, 4)),
+        ('fields', 'Fields', (5, 6, 7, 8, 9)),
+        ('decode', 'Decode', (10,)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.oldpin = None
+        self.last_samplenum = None
+        self.state = 'FFS_SEARCH'
+        self.bits_pos = [[0 for col in range(3)] for row in range(70)]
+        self.br_string = ['RF/8', 'RF/16', 'Unused', 'RF/32', 'RF/40',
+                          'Unused', 'Unused', 'RF/64',]
+        self.encoder = ['not used', 'Manchester', 'Bi-phase', 'not used']
+        self.delayed_on = ['No delay', 'Delayed on - BP/8', 'Delayed on - BP/4', 'No delay']
+        self.em4100_decode1_partial = 0
+        self.cmds = ['Invalid', 'Login', 'Write word', 'Invalid', 'Read word', 'Disable', 'Protect', 'Invalid']
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+        self.field_clock = self.samplerate / self.options['coilfreq']
+        self.wzmax = self.options['w_zero_off_max'] * self.field_clock
+        self.wzmin = self.options['w_zero_on_min'] * self.field_clock
+        self.womax = self.options['w_one_max'] * self.field_clock
+        self.ffs = self.options['first_field_stop'] * self.field_clock
+        self.writegap = self.options['w_gap'] * self.field_clock
+        self.nogap = 300 * self.field_clock
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def decode_config(self, idx):
+        bitrate = self.get_3_bits(idx+2)
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+5][2],
+                 self.out_ann, [10, ['Data rate: ' + \
+                 self.br_string[bitrate], self.br_string[bitrate]]])
+        encoding = self.bits_pos[idx+6][0]<<0 | self.bits_pos[idx+7][0]<<1
+        self.put(self.bits_pos[idx+6][1], self.bits_pos[idx+10][2],
+                 self.out_ann, [10, ['Encoder: ' + \
+                 self.encoder[encoding], self.encoder[encoding]]])
+        self.put(self.bits_pos[idx+11][1], self.bits_pos[idx+12][2], self.out_ann,
+                 [10, ['Zero bits', 'ZB']])
+        delay_on = self.bits_pos[idx+13][0]<<0 | self.bits_pos[idx+14][0]<<1
+        self.put(self.bits_pos[idx+13][1], self.bits_pos[idx+14][2],
+                 self.out_ann, [10, ['Delayed on: ' + \
+                 self.delayed_on[delay_on], self.delayed_on[delay_on]]])
+        lwr = self.bits_pos[idx+15][0]<<3 | self.bits_pos[idx+16][0]<<2 | \
+                 self.bits_pos[idx+18][0]<<1 | self.bits_pos[idx+19][0]<<0
+        self.put(self.bits_pos[idx+15][1], self.bits_pos[idx+19][2],
+                 self.out_ann, [10, ['Last default read word: %d' % lwr, 'LWR: %d' % lwr, '%d' % lwr]])
+        self.put(self.bits_pos[idx+20][1], self.bits_pos[idx+20][2],
+                 self.out_ann, [10, ['Read login: %d' % self.bits_pos[idx+20][0], '%d' % self.bits_pos[idx+20][0]]])
+        self.put(self.bits_pos[idx+21][1], self.bits_pos[idx+21][2], self.out_ann,
+                 [10, ['Zero bits', 'ZB']])
+        self.put(self.bits_pos[idx+22][1], self.bits_pos[idx+22][2],
+                 self.out_ann, [10, ['Write login: %d' % self.bits_pos[idx+22][0], '%d' % self.bits_pos[idx+22][0]]])
+        self.put(self.bits_pos[idx+23][1], self.bits_pos[idx+24][2], self.out_ann,
+                 [10, ['Zero bits', 'ZB']])
+        self.put(self.bits_pos[idx+25][1], self.bits_pos[idx+25][2],
+                 self.out_ann, [10, ['Disable: %d' % self.bits_pos[idx+25][0], '%d' % self.bits_pos[idx+25][0]]])
+        self.put(self.bits_pos[idx+27][1], self.bits_pos[idx+27][2],
+                 self.out_ann, [10, ['Reader talk first: %d' % self.bits_pos[idx+27][0], 'RTF: %d' % self.bits_pos[idx+27][0]]])
+        self.put(self.bits_pos[idx+28][1], self.bits_pos[idx+28][2], self.out_ann,
+                 [10, ['Zero bits', 'ZB']])
+        self.put(self.bits_pos[idx+29][1], self.bits_pos[idx+29][2],
+                 self.out_ann, [10, ['Pigeon mode: %d' % self.bits_pos[idx+29][0], '%d' % self.bits_pos[idx+29][0]]])
+        self.put(self.bits_pos[idx+30][1], self.bits_pos[idx+34][2],
+                 self.out_ann, [10, ['Reserved', 'Res', 'R']])
+
+    def put4bits(self, idx):
+        bits = self.bits_pos[idx][0]<<3 | self.bits_pos[idx+1][0]<<2 | \
+               self.bits_pos[idx+2][0]<<1 | self.bits_pos[idx+3][0]
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+3][2], self.out_ann,
+                 [10, ['%X' % bits]])
+
+    def em4100_decode1(self, idx):
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+9][2], self.out_ann,
+                 [10, ['EM4100 header', 'EM header', 'Header', 'H']])
+        self.put4bits(idx+10)
+        bits = self.bits_pos[idx+15][0]<<3 | self.bits_pos[idx+16][0]<<2 | \
+               self.bits_pos[idx+18][0]<<1 | self.bits_pos[idx+19][0]<<0
+        self.put(self.bits_pos[idx+15][1], self.bits_pos[idx+19][2], self.out_ann,
+               [10, ['%X' % bits]])
+        self.put4bits(idx+21)
+        self.put4bits(idx+27)
+        self.em4100_decode1_partial = self.bits_pos[idx+32][0]<<3 | \
+            self.bits_pos[idx+33][0]<<2 | self.bits_pos[idx+34][0]<<1
+        self.put(self.bits_pos[idx+32][1], self.bits_pos[idx+34][2],
+                 self.out_ann, [10, ['Partial nibble']])
+
+    def em4100_decode2(self, idx):
+        if self.em4100_decode1_partial != 0:
+            bits = self.em4100_decode1_partial + self.bits_pos[idx][0]
+            self.put(self.bits_pos[idx][1], self.bits_pos[idx][2],
+                     self.out_ann, [10, ['%X' % bits]])
+            self.em4100_decode1_partial = 0
+        else:
+            self.put(self.bits_pos[idx][1], self.bits_pos[idx][2],
+                     self.out_ann, [10, ['Partial nibble']])
+
+        self.put4bits(idx+2)
+        bits = self.bits_pos[idx+7][0]<<3 | self.bits_pos[idx+9][0]<<2 | \
+               self.bits_pos[idx+10][0]<<1 | self.bits_pos[idx+11][0]<<0
+        self.put(self.bits_pos[idx+7][1], self.bits_pos[idx+11][2], self.out_ann,
+               [10, ['%X' % bits]])
+        self.put4bits(idx+13)
+        self.put4bits(idx+19)
+        bits = self.bits_pos[idx+24][0]<<3 | self.bits_pos[idx+25][0]<<2 | \
+               self.bits_pos[idx+27][0]<<1 | self.bits_pos[idx+28][0]<<0
+        self.put(self.bits_pos[idx+24][1], self.bits_pos[idx+28][2], self.out_ann,
+               [10, ['%X' % bits]])
+        self.put(self.bits_pos[idx+30][1], self.bits_pos[idx+34][2],
+                 self.out_ann, [10, ['EM4100 trailer']])
+
+    def get_32_bits(self, idx):
+        return self.get_8_bits(idx+27)<<24 | self.get_8_bits(idx+18)<<16 | \
+               self.get_8_bits(idx+9)<<8 | self.get_8_bits(idx)
+
+    def get_8_bits(self, idx):
+        retval = 0
+        for i in range(0, 8):
+            retval <<= 1
+            retval |= self.bits_pos[i+idx][0]
+        return retval
+
+    def get_3_bits(self, idx):
+        return self.bits_pos[idx][0]<<2 | self.bits_pos[idx+1][0]<<1 | \
+               self.bits_pos[idx+2][0]
+
+    def get_4_bits(self, idx):
+        return self.bits_pos[idx][0]<<0 | self.bits_pos[idx+1][0]<<1 | \
+               self.bits_pos[idx+2][0]<<2 | self.bits_pos[idx+3][0]<<3
+
+    def print_row_parity(self, idx, length):
+        parity = 0
+        for i in range(0, length):
+            parity += self.bits_pos[i+idx][0]
+        parity = parity & 0x1
+        if parity == self.bits_pos[idx+length][0]:
+            self.put(self.bits_pos[idx+length][1], self.bits_pos[idx+length][2], self.out_ann,
+                [5, ['Row parity OK', 'Parity OK', 'OK']])
+        else:
+            self.put(self.bits_pos[idx+length][1], self.bits_pos[idx+length][2], self.out_ann,
+                [5, ['Row parity failed', 'Parity failed', 'Fail']])
+
+    def print_col_parity(self, idx):
+        data_1 = self.get_8_bits(idx)
+        data_2 = self.get_8_bits(idx+9)
+        data_3 = self.get_8_bits(idx+9+9)
+        data_4 = self.get_8_bits(idx+9+9+9)
+        col_par = self.get_8_bits(idx+9+9+9+9)
+        col_par_calc = data_1^data_2^data_3^data_4
+
+        if col_par == col_par_calc:
+            self.put(self.bits_pos[idx+9+9+9+9][1], self.bits_pos[idx+9+9+9+9+7][2], self.out_ann,
+                [5, ['Column parity OK', 'Parity OK', 'OK']])
+        else:
+            self.put(self.bits_pos[idx+9+9+9+9][1], self.bits_pos[idx+9+9+9+9+7][2], self.out_ann,
+                [5, ['Column parity failed', 'Parity failed', 'Fail']])
+
+    def print_8bit_data(self, idx):
+        data = self.get_8_bits(idx)
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+7][2], self.out_ann,
+                     [9, ['Data' + ': %X' % data, '%X' % data]])
+
+    def put_fields(self):
+        if self.bit_nr == 50:
+            self.put(self.bits_pos[0][1], self.bits_pos[0][2], self.out_ann,
+                     [4, ['Logic zero']])
+            self.put(self.bits_pos[1][1], self.bits_pos[4][2], self.out_ann,
+                     [4, ['Command', 'Cmd', 'C']])
+            self.put(self.bits_pos[5][1], self.bits_pos[49][2], self.out_ann,
+                     [4, ['Password', 'Passwd', 'Pass', 'P']])
+            # Get command.
+            cmd = self.get_3_bits(1)
+            self.put(self.bits_pos[1][1], self.bits_pos[3][2], self.out_ann,
+                     [5, [self.cmds[cmd]]])
+            self.print_row_parity(1, 3)
+
+            # Print data.
+            self.print_8bit_data(5)
+            self.print_row_parity(5, 8)
+            self.print_8bit_data(14)
+            self.print_row_parity(14, 8)
+            self.print_8bit_data(23)
+            self.print_row_parity(23, 8)
+            self.print_8bit_data(32)
+            self.print_row_parity(32, 8)
+            self.print_col_parity(5)
+            if self.bits_pos[49][0] == 0:
+                self.put(self.bits_pos[49][1], self.bits_pos[49][2], self.out_ann,
+                         [5, ['Stop bit', 'Stop', 'SB']])
+            else:
+                self.put(self.bits_pos[49][1], self.bits_pos[49][2], self.out_ann,
+                         [5, ['Stop bit error', 'Error']])
+
+            if cmd == 1:
+                password = self.get_32_bits(5)
+                self.put(self.bits_pos[12][1], self.bits_pos[46][2], self.out_ann,
+                     [10, ['Login password: %X' % password]])
+
+        if self.bit_nr == 57:
+            self.put(self.bits_pos[0][1], self.bits_pos[0][2], self.out_ann,
+                     [4, ['Logic zero', 'LZ']])
+            self.put(self.bits_pos[1][1], self.bits_pos[4][2], self.out_ann,
+                     [4, ['Command', 'Cmd', 'C']])
+            self.put(self.bits_pos[5][1], self.bits_pos[11][2], self.out_ann,
+                     [4, ['Address', 'Addr', 'A']])
+            self.put(self.bits_pos[12][1], self.bits_pos[56][2], self.out_ann,
+                     [4, ['Data', 'Da', 'D']])
+
+            # Get command.
+            cmd = self.get_3_bits(1)
+            self.put(self.bits_pos[1][1], self.bits_pos[3][2], self.out_ann,
+                     [5, [self.cmds[cmd]]])
+            self.print_row_parity(1, 3)
+
+            # Get address.
+            addr = self.get_4_bits(5)
+            self.put(self.bits_pos[5][1], self.bits_pos[8][2], self.out_ann,
+                     [9, ['Addr' + ': %d' % addr, '%d' % addr]])
+            self.put(self.bits_pos[9][1], self.bits_pos[10][2], self.out_ann,
+                     [5, ['Zero bits', 'ZB']])
+            self.print_row_parity(5, 6)
+            # Print data.
+            self.print_8bit_data(12)
+            self.print_row_parity(12, 8)
+            self.print_8bit_data(21)
+            self.print_row_parity(21, 8)
+            self.print_8bit_data(30)
+            self.print_row_parity(30, 8)
+            self.print_8bit_data(39)
+            self.print_row_parity(39, 8)
+            self.print_col_parity(12)
+            if self.bits_pos[56][0] == 0:
+                self.put(self.bits_pos[56][1], self.bits_pos[56][2], self.out_ann,
+                         [5, ['Stop bit', 'Stop', 'SB']])
+            else:
+                self.put(self.bits_pos[56][1], self.bits_pos[56][2], self.out_ann,
+                         [5, ['Stop bit error', 'Error']])
+
+            if addr == 4:
+                self.decode_config(12)
+
+            if addr == 2:
+                password = self.get_32_bits(12)
+                self.put(self.bits_pos[12][1], self.bits_pos[46][2], self.out_ann,
+                     [10, ['Write password: %X' % password]])
+
+            # If we are programming EM4100 data we can decode it halfway.
+            if addr == 5 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode1(12)
+            if addr == 6 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode2(12)
+
+        self.bit_nr = 0
+
+    def add_bits_pos(self, bit, ss_bit, es_bit):
+        if self.bit_nr < 70:
+            self.bits_pos[self.bit_nr][0] = bit
+            self.bits_pos[self.bit_nr][1] = ss_bit
+            self.bits_pos[self.bit_nr][2] = es_bit
+            self.bit_nr += 1
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, (pin,)) in data:
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpin == pin:
+                continue
+
+            if self.oldpin is None:
+                self.oldpin = pin
+                self.last_samplenum = self.samplenum
+                self.oldsamplenum = 0
+                self.old_gap_end = 0
+                self.gap_detected = 0
+                self.bit_nr = 0
+                continue
+
+            if self.oldpin != pin:
+                pl = self.samplenum - self.oldsamplenum
+                pp = pin
+                samples = self.samplenum - self.last_samplenum
+
+                if self.state == 'FFS_DETECTED':
+                    if pl > self.writegap:
+                        self.gap_detected = 1
+                    if (self.last_samplenum - self.old_gap_end) > self.nogap:
+                        self.gap_detected = 0
+                        self.state = 'FFS_SEARCH'
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [3, ['Write mode exit']])
+                        self.put_fields()
+
+                if self.state == 'FFS_SEARCH':
+                    if pl > self.ffs:
+                        self.gap_detected = 1
+                        self.put(self.last_samplenum, self.samplenum,
+                                 self.out_ann, [1, ['First field stop', 'Field stop', 'FFS']])
+                        self.state = 'FFS_DETECTED'
+
+                if self.gap_detected == 1:
+                    self.gap_detected = 0
+                    if (self.last_samplenum - self.old_gap_end) > self.wzmin \
+                            and (self.last_samplenum - self.old_gap_end) < self.wzmax:
+                        self.put(self.old_gap_end, self.samplenum,
+                                 self.out_ann, [0, ['0']])
+                        self.add_bits_pos(0, self.old_gap_end, self.samplenum)
+                    if (self.last_samplenum - self.old_gap_end) > self.womax \
+                            and (self.last_samplenum-self.old_gap_end) < self.nogap:
+                        # One or more 1 bits
+                        one_bits = (int)((self.last_samplenum - self.old_gap_end) / self.womax)
+                        for ox in range(0, one_bits):
+                            bs = (int)(self.old_gap_end+ox*self.womax)
+                            be = (int)(self.old_gap_end+ox*self.womax + self.womax)
+                            self.put(bs, be, self.out_ann, [0, ['1']])
+                            self.add_bits_pos(1, bs, be)
+                        if (self.samplenum - self.last_samplenum) > self.wzmin \
+                                and (self.samplenum - self.last_samplenum) < self.wzmax:
+                            bs = (int)(self.old_gap_end+one_bits*self.womax)
+                            self.put(bs, self.samplenum, self.out_ann, [0, ['0']])
+                            self.add_bits_pos(0, bs, self.samplenum)
+
+                    self.old_gap_end = self.samplenum
+
+                if self.state == 'SKIP':
+                    self.state = 'FFS_SEARCH'
+
+                self.oldsamplenum = self.samplenum
+                self.last_samplenum = self.samplenum
+                self.oldpin = pin
diff --git a/decoders/ir_nec/__init__.py b/decoders/gpib/__init__.py
similarity index 84%
copy from decoders/ir_nec/__init__.py
copy to decoders/gpib/__init__.py
index 84bf428..3dae563 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/gpib/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2016 Rudolf Reuter <reuterru at arcor.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
@@ -19,8 +19,7 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This protocol decoder can decode the GPIB (IEEE-488) protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/gpib/pd.py b/decoders/gpib/pd.py
new file mode 100644
index 0000000..0712966
--- /dev/null
+++ b/decoders/gpib/pd.py
@@ -0,0 +1,189 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Rudolf Reuter <reuterru at arcor.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'gpib'
+    name = 'GPIB'
+    longname = 'General Purpose Interface Bus'
+    desc = 'IEEE-488 GPIB / HPIB protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['gpib']
+    channels = (
+        {'id': 'dio1' , 'name': 'DIO1', 'desc': 'Data I/O bit 1'},
+        {'id': 'dio2' , 'name': 'DIO2', 'desc': 'Data I/O bit 2'},
+        {'id': 'dio3' , 'name': 'DIO3', 'desc': 'Data I/O bit 3'},
+        {'id': 'dio4' , 'name': 'DIO4', 'desc': 'Data I/O bit 4'},
+        {'id': 'dio5' , 'name': 'DIO5', 'desc': 'Data I/O bit 5'},
+        {'id': 'dio6' , 'name': 'DIO6', 'desc': 'Data I/O bit 6'},
+        {'id': 'dio7' , 'name': 'DIO7', 'desc': 'Data I/O bit 7'},
+        {'id': 'dio8' , 'name': 'DIO8', 'desc': 'Data I/O bit 8'},
+        {'id': 'eoi', 'name': 'EOI', 'desc': 'End or identify'},
+        {'id': 'dav', 'name': 'DAV', 'desc': 'Data valid'},
+        {'id': 'nrfd', 'name': 'NRFD', 'desc': 'Not ready for data'},
+        {'id': 'ndac', 'name': 'NDAC', 'desc': 'Not data accepted'},
+        {'id': 'ifc', 'name': 'IFC', 'desc': 'Interface clear'},
+        {'id': 'srq', 'name': 'SRQ', 'desc': 'Service request'},
+        {'id': 'atn', 'name': 'ATN', 'desc': 'Attention'},
+        {'id': 'ren', 'name': 'REN', 'desc': 'Remote enable'},
+    )
+    options = (
+        {'id': 'sample_total', 'desc': 'Total number of samples', 'default': 0},
+    )
+    annotations = (
+        ('items', 'Items'),
+        ('gpib', 'DAT/CMD'),
+        ('eoi', 'EOI'),
+    )
+    annotation_rows = (
+        ('bytes', 'Bytes', (0,)),
+        ('gpib', 'DAT/CMD', (1,)),
+        ('eoi', 'EOI', (2,)),
+    )
+
+    def __init__(self):
+        self.olddav = None
+        self.items = []
+        self.itemcount = 0
+        self.saved_item = None
+        self.saved_ATN = False
+        self.saved_EOI = False
+        self.samplenum = 0
+        self.oldpins = None
+        self.ss_item = self.es_item = None
+        self.first = True
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putb(self, data):
+        self.put(self.ss_item, self.es_item, self.out_ann, data)
+
+    def handle_bits(self, datapins):
+        dbyte = 0x20
+        dATN = False
+        item2 = False
+        dEOI = False
+        item3 = False
+        # If this is the first item in a word, save its sample number.
+        if self.itemcount == 0:
+            self.ss_word = self.samplenum
+
+        # Get the bits for this item.
+        item = 0
+        for i in range(8):
+            item |= datapins[i] << i
+
+        item = item ^ 0xff # Invert data byte.
+        self.items.append(item)
+        self.itemcount += 1
+
+        if datapins[14] == 0:
+            item2 = True
+        if datapins[8] == 0:
+            item3 = True
+
+        if self.first:
+            # Save the start sample and item for later (no output yet).
+            self.ss_item = self.samplenum
+            self.first = False
+            self.saved_item = item
+            self.saved_ATN = item2
+            self.saved_EOI = item3
+        else:
+            # Output the saved item.
+            dbyte = self.saved_item
+            dATN = self.saved_ATN
+            dEOI = self.saved_EOI
+            self.es_item = self.samplenum
+            self.putb([0, ['%02X' % self.saved_item]])
+
+            # Encode item byte to GPIB convention.
+            self.strgpib = ' '
+            if dATN: # ATN, decode commands.
+                if dbyte == 0x01: self.strgpib = 'GTL'
+                if dbyte == 0x04: self.strgpib = 'SDC'
+                if dbyte == 0x05: self.strgpib = 'PPC'
+                if dbyte == 0x08: self.strgpib = 'GET'
+                if dbyte == 0x09: self.strgpib = 'TCT'
+                if dbyte == 0x11: self.strgpib = 'LLO'
+                if dbyte == 0x14: self.strgpib = 'DCL'
+                if dbyte == 0x15: self.strgpib = 'PPU'
+                if dbyte == 0x18: self.strgpib = 'SPE'
+                if dbyte == 0x19: self.strgpib = 'SPD'
+                if dbyte == 0x3f: self.strgpib = 'UNL'
+                if dbyte == 0x5f: self.strgpib = 'UNT'
+                if dbyte > 0x1f and dbyte < 0x3f: # Address Listener.
+                    self.strgpib = 'L' + chr(dbyte + 0x10)
+                if dbyte > 0x3f and dbyte < 0x5f: # Address Talker
+                    self.strgpib = 'T' + chr(dbyte - 0x10)
+            else:
+                if dbyte > 0x1f and dbyte < 0x7f:
+                    self.strgpib = chr(dbyte)
+                if dbyte == 0x0a:
+                    self.strgpib = 'LF'
+                if dbyte == 0x0d:
+                    self.strgpib = 'CR'
+
+            self.putb([1, [self.strgpib]])
+            self.strEOI = ' '
+            if dEOI:
+                self.strEOI = 'EOI'
+            self.putb([2, [self.strEOI]])
+
+            self.ss_item = self.samplenum
+            self.saved_item = item
+            self.saved_ATN = item2
+            self.saved_EOI = item3
+
+        if self.itemcount < 16:
+            return
+
+        self.itemcount, self.items = 0, []
+
+    def find_falling_dav_edge(self, dav, datapins):
+        # Ignore sample if the DAV pin hasn't changed.
+        if dav == self.olddav:
+            return
+        self.olddav = dav
+        # Sample on falling DAV edge.
+        if dav == 1:
+            return
+
+        # Found the correct DAV edge, now get the bits.
+        self.handle_bits(datapins)
+
+    def decode(self, ss, es, data):
+        lsn = self.options['sample_total']
+
+        for (self.samplenum, pins) in data:
+            if lsn > 0:
+                if (lsn - self.samplenum) == 1: # Show the last data word.
+                    self.handle_bits(pins)
+
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpins == pins:
+                continue
+            self.oldpins = pins
+
+            self.find_falling_dav_edge(pins[9], pins)
diff --git a/decoders/guess_bitrate/__init__.py b/decoders/guess_bitrate/__init__.py
index 9c7e6a4..cd8f15e 100644
--- a/decoders/guess_bitrate/__init__.py
+++ b/decoders/guess_bitrate/__init__.py
@@ -34,5 +34,4 @@ recommended to use a logic analyzer samplerate that is much higher than
 the expected bitrate/baudrate that might be used on the channel.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/guess_bitrate/pd.py b/decoders/guess_bitrate/pd.py
index e86316f..92d3520 100644
--- a/decoders/guess_bitrate/pd.py
+++ b/decoders/guess_bitrate/pd.py
@@ -20,6 +20,9 @@
 
 import sigrokdecode as srd
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'guess_bitrate'
@@ -39,7 +42,7 @@ class Decoder(srd.Decoder):
     def putx(self, data):
         self.put(self.ss_edge, self.samplenum, self.out_ann, data)
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.olddata = None
         self.ss_edge = None
         self.first_transition = True
@@ -50,11 +53,11 @@ class Decoder(srd.Decoder):
 
     def metadata(self, key, value):
         if key == srd.SRD_CONF_SAMPLERATE:
-            self.samplerate = value;
+            self.samplerate = value
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
             data = pins[0]
@@ -64,22 +67,21 @@ class Decoder(srd.Decoder):
                 continue
 
             # Initialize first self.olddata with the first sample value.
-            if self.olddata == None:
+            if self.olddata is None:
                 self.olddata = data
                 continue
 
             # Get the smallest distance between two transitions
             # and use that to calculate the bitrate/baudrate.
-            if self.first_transition == True:
+            if self.first_transition:
                 self.ss_edge = self.samplenum
                 self.first_transition = False
             else:
                 b = self.samplenum - self.ss_edge
-                if self.bitwidth == None or b < self.bitwidth:
+                if self.bitwidth is None or b < self.bitwidth:
                     self.bitwidth = b
                     bitrate = int(float(self.samplerate) / float(b))
                     self.putx([0, ['%d' % bitrate]])
                 self.ss_edge = self.samplenum
 
             self.olddata = data
-
diff --git a/decoders/i2c/__init__.py b/decoders/i2c/__init__.py
index ba40245..c3b0cd5 100644
--- a/decoders/i2c/__init__.py
+++ b/decoders/i2c/__init__.py
@@ -23,5 +23,4 @@ I²C (Inter-Integrated Circuit) is a bidirectional, multi-master
 bus using two signals (SCL = serial clock line, SDA = serial data line).
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/i2c/pd.py b/decoders/i2c/pd.py
index 2d6e5c2..a056ef5 100644
--- a/decoders/i2c/pd.py
+++ b/decoders/i2c/pd.py
@@ -63,6 +63,9 @@ proto = {
     'DATA WRITE':      [9, 'Data write',    'DW'],
 }
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'i2c'
@@ -105,9 +108,9 @@ class Decoder(srd.Decoder):
         ('data-write', 'Data write'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
-        self.ss = self.es = self.byte_ss = -1
+        self.ss = self.es = self.ss_byte = -1
         self.samplenum = None
         self.bitcount = 0
         self.databyte = 0
@@ -179,7 +182,7 @@ class Decoder(srd.Decoder):
 
         # Remember the start of the first data/address bit.
         if self.bitcount == 0:
-            self.byte_ss = self.samplenum
+            self.ss_byte = self.samplenum
 
         # Store individual bits and their start/end samplenumbers.
         # In the list, index 0 represents the LSB (I²C transmits MSB-first).
@@ -216,12 +219,12 @@ class Decoder(srd.Decoder):
             cmd = 'DATA READ'
             bin_class = 2
 
-        self.ss, self.es = self.byte_ss, self.samplenum + self.bitwidth
+        self.ss, self.es = self.ss_byte, self.samplenum + self.bitwidth
 
         self.putp(['BITS', self.bits])
         self.putp([cmd, d])
 
-        self.putb((bin_class, bytes([d])))
+        self.putb([bin_class, bytes([d])])
 
         for bit in self.bits:
             self.put(bit[1], bit[2], self.out_ann, [5, ['%d' % bit[0]]])
@@ -230,7 +233,7 @@ class Decoder(srd.Decoder):
             self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
             w = ['Write', 'Wr', 'W'] if self.wr else ['Read', 'Rd', 'R']
             self.putx([proto[cmd][0], w])
-            self.ss, self.es = self.byte_ss, self.samplenum
+            self.ss, self.es = self.ss_byte, self.samplenum
 
         self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
                    '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
@@ -253,7 +256,7 @@ class Decoder(srd.Decoder):
         # Meta bitrate
         elapsed = 1 / float(self.samplerate) * (self.samplenum - self.pdu_start + 1)
         bitrate = int(1 / elapsed * self.pdu_bits)
-        self.put(self.byte_ss, self.samplenum, self.out_bitrate, bitrate)
+        self.put(self.ss_byte, self.samplenum, self.out_bitrate, bitrate)
 
         cmd = 'STOP'
         self.ss, self.es = self.samplenum, self.samplenum
@@ -265,8 +268,8 @@ class Decoder(srd.Decoder):
         self.bits = []
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
             # Ignore identical samples early on (for performance reasons).
@@ -293,9 +296,6 @@ class Decoder(srd.Decoder):
             elif self.state == 'FIND ACK':
                 if self.is_data_bit(scl, sda):
                     self.get_ack(scl, sda)
-            else:
-                raise Exception('Invalid state: %s' % self.state)
 
             # Save current SDA/SCL values for the next round.
             self.oldscl, self.oldsda = scl, sda
-
diff --git a/decoders/i2cdemux/__init__.py b/decoders/i2cdemux/__init__.py
index c5202c5..75fcd86 100644
--- a/decoders/i2cdemux/__init__.py
+++ b/decoders/i2cdemux/__init__.py
@@ -25,5 +25,4 @@ It takes an I²C stream as input and outputs multiple I²C streams, each
 stream containing only I²C packets for one specific I²C slave.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/i2cdemux/pd.py b/decoders/i2cdemux/pd.py
index e5cf47a..5e83a21 100644
--- a/decoders/i2cdemux/pd.py
+++ b/decoders/i2cdemux/pd.py
@@ -30,7 +30,7 @@ class Decoder(srd.Decoder):
     inputs = ['i2c']
     outputs = [] # TODO: Only known at run-time.
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.packets = [] # Local cache of I²C packets
         self.slaves = [] # List of known slave addresses
         self.stream = -1 # Current output stream
@@ -75,4 +75,3 @@ class Decoder(srd.Decoder):
             self.stream = -1
         else:
             pass # Do nothing, only add the I²C packet to our cache.
-
diff --git a/decoders/i2cfilter/__init__.py b/decoders/i2cfilter/__init__.py
index 6cbab8a..be97bf0 100644
--- a/decoders/i2cfilter/__init__.py
+++ b/decoders/i2cfilter/__init__.py
@@ -34,5 +34,4 @@ Both of these are optional; if no options are specified the entire payload
 of the I²C session will be output.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/i2cfilter/pd.py b/decoders/i2cfilter/pd.py
index f1ac6a4..c3f148f 100644
--- a/decoders/i2cfilter/pd.py
+++ b/decoders/i2cfilter/pd.py
@@ -38,8 +38,7 @@ class Decoder(srd.Decoder):
             'values': ('read', 'write', 'both')}
     )
 
-    def __init__(self, **kwargs):
-        self.state = None
+    def __init__(self):
         self.curslave = -1
         self.curdirection = None
         self.packets = [] # Local cache of I²C packets
@@ -48,8 +47,6 @@ class Decoder(srd.Decoder):
         self.out_python = self.register(srd.OUTPUT_PYTHON, proto_id='i2c')
         if self.options['address'] not in range(0, 127 + 1):
             raise Exception('Invalid slave (must be 0..127).')
-        if self.options['direction'] not in ('both', 'read', 'write'):
-            raise Exception('Invalid direction (valid: read/write/both).')
 
     # Grab I²C packets into a local cache, until an I²C STOP condition
     # packet comes along. At some point before that STOP condition, there
@@ -90,4 +87,3 @@ class Decoder(srd.Decoder):
             self.packets = []
         else:
             pass # Do nothing, only add the I²C packet to our cache.
-
diff --git a/decoders/i2s/__init__.py b/decoders/i2s/__init__.py
index b9c0ed7..e114cd0 100644
--- a/decoders/i2s/__init__.py
+++ b/decoders/i2s/__init__.py
@@ -27,5 +27,4 @@ http://www.nxp.com/acrobat_download/various/I2SBUS.pdf
 http://en.wikipedia.org/wiki/I2s
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/i2s/pd.py b/decoders/i2s/pd.py
index 989a5a5..3287a72 100644
--- a/decoders/i2s/pd.py
+++ b/decoders/i2s/pd.py
@@ -33,6 +33,9 @@ Packet:
 <value>: integer
 '''
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'i2s'
@@ -56,7 +59,7 @@ class Decoder(srd.Decoder):
         ('wav', 'WAV file'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.oldsck = 1
         self.oldws = 1
@@ -64,13 +67,13 @@ class Decoder(srd.Decoder):
         self.data = 0
         self.samplesreceived = 0
         self.first_sample = None
-        self.start_sample = None
+        self.ss_block = None
         self.wordlength = -1
         self.wrote_wav_header = False
 
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
-        self.out_bin = self.register(srd.OUTPUT_BINARY)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def metadata(self, key, value):
@@ -78,23 +81,23 @@ class Decoder(srd.Decoder):
             self.samplerate = value
 
     def putpb(self, data):
-        self.put(self.start_sample, self.samplenum, self.out_python, data)
+        self.put(self.ss_block, self.samplenum, self.out_python, data)
 
     def putbin(self, data):
-        self.put(self.start_sample, self.samplenum, self.out_bin, data)
+        self.put(self.ss_block, self.samplenum, self.out_binary, data)
 
     def putb(self, data):
-        self.put(self.start_sample, self.samplenum, self.out_ann, data)
+        self.put(self.ss_block, self.samplenum, self.out_ann, data)
 
     def report(self):
 
         # Calculate the sample rate.
         samplerate = '?'
-        if self.start_sample != None and \
-            self.first_sample != None and \
-            self.start_sample > self.first_sample:
+        if self.ss_block is not None and \
+            self.first_sample is not None and \
+            self.ss_block > self.first_sample:
             samplerate = '%d' % (self.samplesreceived *
-                self.samplerate / (self.start_sample -
+                self.samplerate / (self.ss_block -
                 self.first_sample))
 
         return 'I²S: %d %d-bit samples received at %sHz' % \
@@ -128,8 +131,8 @@ class Decoder(srd.Decoder):
         return bytes([lo, hi])
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for self.samplenum, (sck, ws, sd) in data:
 
             # Ignore sample if the bit clock hasn't changed.
@@ -148,10 +151,10 @@ class Decoder(srd.Decoder):
                 continue
 
             # Only submit the sample, if we received the beginning of it.
-            if self.start_sample != None:
+            if self.ss_block is not None:
 
                 if not self.wrote_wav_header:
-                    self.put(0, 0, self.out_bin, (0, self.wav_header()))
+                    self.put(0, 0, self.out_binary, [0, self.wav_header()])
                     self.wrote_wav_header = True
 
                 self.samplesreceived += 1
@@ -164,7 +167,7 @@ class Decoder(srd.Decoder):
                 self.putpb(['DATA', [c3, self.data]])
                 self.putb([idx, ['%s: %s' % (c1, v), '%s: %s' % (c2, v),
                                  '%s: %s' % (c3, v), c3]])
-                self.putbin((0, self.wav_sample(self.data)))
+                self.putbin([0, self.wav_sample(self.data)])
 
                 # Check that the data word was the correct length.
                 if self.wordlength != -1 and self.wordlength != self.bitcount:
@@ -176,11 +179,10 @@ class Decoder(srd.Decoder):
             # Reset decoder state.
             self.data = 0
             self.bitcount = 0
-            self.start_sample = self.samplenum
+            self.ss_block = self.samplenum
 
             # Save the first sample position.
-            if self.first_sample == None:
+            if self.first_sample is None:
                 self.first_sample = self.samplenum
 
             self.oldws = ws
-
diff --git a/decoders/ir_nec/__init__.py b/decoders/ir_nec/__init__.py
index 84bf428..6b15f19 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/ir_nec/__init__.py
@@ -22,5 +22,4 @@
 NEC is a pulse-distance based infrared remote control protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/ir_nec/lists.py b/decoders/ir_nec/lists.py
index c9dc595..3f730d9 100644
--- a/decoders/ir_nec/lists.py
+++ b/decoders/ir_nec/lists.py
@@ -49,4 +49,3 @@ command = {
         68: ['AV', 'AV'],
     }.items())),
 }
-
diff --git a/decoders/ir_nec/pd.py b/decoders/ir_nec/pd.py
index 94e232f..8c589fa 100644
--- a/decoders/ir_nec/pd.py
+++ b/decoders/ir_nec/pd.py
@@ -21,6 +21,9 @@
 import sigrokdecode as srd
 from .lists import *
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'ir_nec'
@@ -96,7 +99,7 @@ class Decoder(srd.Decoder):
                  [11, ['%s: %s' % (dev, btn[0]), '%s: %s' % (dev, btn[1]),
                  '%s' % btn[1]]])
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.ss_bit = self.ss_start = self.ss_other_edge = self.ss_remote = 0
         self.data = self.count = self.active = self.old_ir = None
@@ -148,8 +151,8 @@ class Decoder(srd.Decoder):
         return ret == 0
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
             self.ir = pins[0]
 
@@ -199,8 +202,5 @@ class Decoder(srd.Decoder):
                 self.putremote()
                 self.ss_bit = self.ss_start = self.samplenum
                 self.state = 'IDLE'
-            else:
-                raise Exception('Invalid state: %s' % self.state)
 
             self.old_ir = self.ir
-
diff --git a/decoders/ir_rc5/__init__.py b/decoders/ir_rc5/__init__.py
index 085082f..8f5f5a3 100644
--- a/decoders/ir_rc5/__init__.py
+++ b/decoders/ir_rc5/__init__.py
@@ -22,5 +22,4 @@
 RC-5 is a biphase/manchester based infrared remote control protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/ir_rc5/lists.py b/decoders/ir_rc5/lists.py
index 8a81ef7..2ac227e 100644
--- a/decoders/ir_rc5/lists.py
+++ b/decoders/ir_rc5/lists.py
@@ -92,4 +92,3 @@ command = {
         55: ['Recording', 'Rec'],
     }.items())),
 }
-
diff --git a/decoders/ir_rc5/pd.py b/decoders/ir_rc5/pd.py
index 38b4793..ae20d3a 100644
--- a/decoders/ir_rc5/pd.py
+++ b/decoders/ir_rc5/pd.py
@@ -21,6 +21,9 @@
 import sigrokdecode as srd
 from .lists import *
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'ir_rc5'
@@ -53,10 +56,10 @@ class Decoder(srd.Decoder):
         ('fields', 'Fields', (1, 2, 3, 4, 5, 6)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.samplenum = None
-        self.edges, self.bits, self.bits_ss_es = [], [], []
+        self.edges, self.bits, self.ss_es_bits = [], [], []
         self.state = 'IDLE'
 
     def start(self):
@@ -70,7 +73,7 @@ class Decoder(srd.Decoder):
             self.halfbit = int((self.samplerate * 0.00178) / 2.0)
 
     def putb(self, bit1, bit2, data):
-        ss, es = self.bits_ss_es[bit1][0], self.bits_ss_es[bit2][1]
+        ss, es = self.ss_es_bits[bit1][0], self.ss_es_bits[bit2][1]
         self.put(ss, es, self.out_ann, data)
 
     def handle_bits(self):
@@ -80,9 +83,9 @@ class Decoder(srd.Decoder):
             if i == 0:
                 ss = max(0, self.bits[0][0] - self.halfbit)
             else:
-                ss = self.bits_ss_es[i - 1][1]
+                ss = self.ss_es_bits[i - 1][1]
             es = self.bits[i][0] + self.halfbit
-            self.bits_ss_es.append([ss, es])
+            self.ss_es_bits.append([ss, es])
             self.putb(i, i, [0, ['%d' % self.bits[i][1]]])
         # Bits[0:0]: Startbit 1
         s = ['Startbit1: %d' % b[0][1], 'SB1: %d' % b[0][1], 'SB1', 'S1', 'S']
@@ -129,12 +132,12 @@ class Decoder(srd.Decoder):
             return 'e' # Error, invalid edge distance.
 
     def reset_decoder_state(self):
-        self.edges, self.bits, self.bits_ss_es = [], [], []
+        self.edges, self.bits, self.ss_es_bits = [], [], []
         self.state = 'IDLE'
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
             self.ir = pins[0]
@@ -168,11 +171,9 @@ class Decoder(srd.Decoder):
                 if edge == 's':
                     self.state = 'MID0'
                 bit = 0 if edge == 's' else None
-            else:
-                raise Exception('Invalid state: %s' % self.state)
 
             self.edges.append(self.samplenum)
-            if bit != None:
+            if bit is not None:
                 self.bits.append([self.samplenum, bit])
 
             if len(self.bits) == 14:
@@ -180,4 +181,3 @@ class Decoder(srd.Decoder):
                 self.reset_decoder_state()
 
             self.old_ir = self.ir
-
diff --git a/decoders/dcf77/__init__.py b/decoders/jitter/__init__.py
similarity index 65%
copy from decoders/dcf77/__init__.py
copy to decoders/jitter/__init__.py
index 04805c2..e223e73 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/jitter/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
 ##
 ## 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
@@ -19,12 +19,11 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This protocol decoder retrieves the timing jitter between two digital signals.
 
-Details:
-http://en.wikipedia.org/wiki/DCF77
+It allows to define a clock source channel and a resulting signal channel.
+Each time a significant edge is detected in the clock source, we calculate the
+elapsed time before the resulting signal answers and report the timing jitter.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/jitter/pd.py b/decoders/jitter/pd.py
new file mode 100644
index 0000000..c3579a8
--- /dev/null
+++ b/decoders/jitter/pd.py
@@ -0,0 +1,203 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+# Helper dictionary for edge detection.
+edge_detector = {
+    'rising':  lambda x, y: bool(not x and y),
+    'falling': lambda x, y: bool(x and not y),
+    'both':    lambda x, y: bool(x ^ y),
+}
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'jitter'
+    name = 'Jitter'
+    longname = 'Timing jitter calculation'
+    desc = 'Retrieves the timing jitter between two digital signals.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['jitter']
+    channels = (
+        {'id': 'clk', 'name': 'Clock', 'desc': 'Clock reference channel'},
+        {'id': 'sig', 'name': 'Resulting signal', 'desc': 'Resulting signal controlled by the clock'},
+    )
+    options = (
+        {'id': 'clk_polarity', 'desc': 'Clock edge polarity',
+            'default': 'rising', 'values': ('rising', 'falling', 'both')},
+        {'id': 'sig_polarity', 'desc': 'Resulting signal edge polarity',
+            'default': 'rising', 'values': ('rising', 'falling', 'both')},
+    )
+    annotations = (
+        ('jitter', 'Jitter value'),
+        ('clk_missed', 'Clock missed'),
+        ('sig_missed', 'Signal missed'),
+    )
+    annotation_rows = (
+        ('jitter', 'Jitter values', (0,)),
+        ('clk_missed', 'Clock missed', (1,)),
+        ('sig_missed', 'Signal missed', (2,)),
+    )
+    binary = (
+        ('ascii-float', 'Jitter values as newline-separated ASCII floats'),
+    )
+
+    def __init__(self):
+        self.state = 'CLK'
+        self.samplerate = None
+        self.oldpin = None
+        self.oldclk = self.oldsig = None
+        self.clk_start = None
+        self.sig_start = None
+        self.clk_missed = 0
+        self.sig_missed = 0
+
+    def start(self):
+        self.clk_edge = edge_detector[self.options['clk_polarity']]
+        self.sig_edge = edge_detector[self.options['sig_polarity']]
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+        self.out_clk_missed = self.register(srd.OUTPUT_META,
+            meta=(int, 'Clock missed', 'Clock transition missed'))
+        self.out_sig_missed = self.register(srd.OUTPUT_META,
+            meta=(int, 'Signal missed', 'Resulting signal transition missed'))
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    # Helper function for jitter time annotations.
+    def putx(self, delta):
+        # Adjust granularity.
+        if delta == 0 or delta >= 1:
+            delta_s = '%.1fs' % (delta)
+        elif delta <= 1e-12:
+            delta_s = '%.1ffs' % (delta * 1e15)
+        elif delta <= 1e-9:
+            delta_s = '%.1fps' % (delta * 1e12)
+        elif delta <= 1e-6:
+            delta_s = '%.1fns' % (delta * 1e9)
+        elif delta <= 1e-3:
+            delta_s = '%.1fμs' % (delta * 1e6)
+        else:
+            delta_s = '%.1fms' % (delta * 1e3)
+
+        self.put(self.clk_start, self.sig_start, self.out_ann, [0, [delta_s]])
+
+    # Helper function for ASCII float jitter values (one value per line).
+    def putb(self, delta):
+        if delta is None:
+            return
+        # Format the delta to an ASCII float value terminated by a newline.
+        x = str(delta) + '\n'
+        self.put(self.clk_start, self.sig_start, self.out_binary,
+                 [0, x.encode('UTF-8')])
+
+    # Helper function for missed clock and signal annotations.
+    def putm(self, data):
+        self.put(self.samplenum, self.samplenum, self.out_ann, data)
+
+    def handle_clk(self, clk, sig):
+        if self.clk_start == self.samplenum:
+            # Clock transition already treated.
+            # We have done everything we can with this sample.
+            return True
+
+        if self.clk_edge(self.oldclk, clk):
+            # Clock edge found.
+            # We note the sample and move to the next state.
+            self.clk_start = self.samplenum
+            self.state = 'SIG'
+            return False
+        else:
+            if self.sig_start is not None \
+               and self.sig_start != self.samplenum \
+               and self.sig_edge(self.oldsig, sig):
+                # If any transition in the resulting signal
+                # occurs while we are waiting for a clock,
+                # we increase the missed signal counter.
+                self.sig_missed += 1
+                self.put(self.samplenum, self.samplenum, self.out_sig_missed, self.sig_missed)
+                self.putm([2, ['Missed signal', 'MS']])
+            # No clock edge found, we have done everything we
+            # can with this sample.
+            return True
+
+    def handle_sig(self, clk, sig):
+        if self.sig_start == self.samplenum:
+            # Signal transition already treated.
+            # We have done everything we can with this sample.
+            return True
+
+        if self.sig_edge(self.oldsig, sig):
+            # Signal edge found.
+            # We note the sample, calculate the jitter
+            # and move to the next state.
+            self.sig_start = self.samplenum
+            self.state = 'CLK'
+            # Calculate and report the timing jitter.
+            delta = (self.sig_start - self.clk_start) / self.samplerate
+            self.putx(delta)
+            self.putb(delta)
+            return False
+        else:
+            if self.clk_start != self.samplenum \
+               and self.clk_edge(self.oldclk, clk):
+                # If any transition in the clock signal
+                # occurs while we are waiting for a resulting
+                # signal, we increase the missed clock counter.
+                self.clk_missed += 1
+                self.put(self.samplenum, self.samplenum, self.out_clk_missed, self.clk_missed)
+                self.putm([1, ['Missed clock', 'MC']])
+            # No resulting signal edge found, we have done
+            # everything we can with this sample.
+            return True
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+
+        for (self.samplenum, pins) in data:
+            # We are only interested in transitions.
+            if self.oldpin == pins:
+                continue
+
+            self.oldpin, (clk, sig) = pins, pins
+
+            if self.oldclk is None and self.oldsig is None:
+                self.oldclk, self.oldsig = clk, sig
+
+            # State machine:
+            # For each sample we can move 2 steps forward in the state machine.
+            while True:
+                # Clock state has the lead.
+                if self.state == 'CLK':
+                    if self.handle_clk(clk, sig):
+                        break
+                if self.state == 'SIG':
+                    if self.handle_sig(clk, sig):
+                        break
+
+            # Save current CLK/SIG values for the next round.
+            self.oldclk, self.oldsig = clk, sig
diff --git a/decoders/jtag/__init__.py b/decoders/jtag/__init__.py
index 047e54a..863ef09 100644
--- a/decoders/jtag/__init__.py
+++ b/decoders/jtag/__init__.py
@@ -28,5 +28,4 @@ https://en.wikipedia.org/wiki/Joint_Test_Action_Group
 http://focus.ti.com/lit/an/ssya002c/ssya002c.pdf
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/jtag/pd.py b/decoders/jtag/pd.py
index 25f2634..83d4b28 100644
--- a/decoders/jtag/pd.py
+++ b/decoders/jtag/pd.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012-2013 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2015 Uwe Hermann <uwe at hermann-uwe.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
@@ -36,10 +36,11 @@ Packet:
  - 'IR TDO': Bitstring that was clocked out of the IR register.
  - 'DR TDI': Bitstring that was clocked into the DR register.
  - 'DR TDO': Bitstring that was clocked out of the DR register.
- - ...
 
-All bitstrings are a sequence of '1' and '0' characters. The right-most
-character in the bitstring is the LSB. Example: '01110001' (1 is LSB).
+All bitstrings are a list consisting of two items. The first is a sequence
+of '1' and '0' characters (the right-most character is the LSB. Example:
+'01110001', where 1 is the LSB). The second item is a list of ss/es values
+for each bit that is in the bitstring.
 '''
 
 jtag_states = [
@@ -73,9 +74,21 @@ class Decoder(srd.Decoder):
         {'id': 'srst', 'name': 'SRST#', 'desc': 'System reset'},
         {'id': 'rtck', 'name': 'RTCK',  'desc': 'Return clock signal'},
     )
-    annotations = tuple([tuple([s.lower(), s]) for s in jtag_states])
+    annotations = tuple([tuple([s.lower(), s]) for s in jtag_states]) + ( \
+        ('bit-tdi', 'Bit (TDI)'),
+        ('bit-tdo', 'Bit (TDO)'),
+        ('bitstring-tdi', 'Bitstring (TDI)'),
+        ('bitstring-tdo', 'Bitstring (TDO)'),
+    )
+    annotation_rows = (
+        ('bits-tdi', 'Bits (TDI)', (16,)),
+        ('bits-tdo', 'Bits (TDO)', (17,)),
+        ('bitstrings-tdi', 'Bitstring (TDI)', (18,)),
+        ('bitstrings-tdo', 'Bitstring (TDO)', (19,)),
+        ('states', 'States', tuple(range(15 + 1))),
+    )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         # self.state = 'TEST-LOGIC-RESET'
         self.state = 'RUN-TEST/IDLE'
         self.oldstate = None
@@ -83,10 +96,14 @@ class Decoder(srd.Decoder):
         self.oldtck = -1
         self.bits_tdi = []
         self.bits_tdo = []
+        self.bits_samplenums_tdi = []
+        self.bits_samplenums_tdo = []
         self.samplenum = 0
         self.ss_item = self.es_item = None
+        self.ss_bitstring = self.es_bitstring = None
         self.saved_item = None
         self.first = True
+        self.first_bit = True
 
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
@@ -98,6 +115,12 @@ class Decoder(srd.Decoder):
     def putp(self, data):
         self.put(self.ss_item, self.es_item, self.out_python, data)
 
+    def putx_bs(self, data):
+        self.put(self.ss_bitstring, self.es_bitstring, self.out_ann, data)
+
+    def putp_bs(self, data):
+        self.put(self.ss_bitstring, self.es_bitstring, self.out_python, data)
+
     def advance_state_machine(self, tms):
         self.oldstate = self.state
 
@@ -139,55 +162,73 @@ class Decoder(srd.Decoder):
         elif self.state == 'UPDATE-IR':
             self.state = 'SELECT-DR-SCAN' if (tms) else 'RUN-TEST/IDLE'
 
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
     def handle_rising_tck_edge(self, tdi, tdo, tck, tms):
         # Rising TCK edges always advance the state machine.
         self.advance_state_machine(tms)
 
-        if self.first == True:
+        if self.first:
             # Save the start sample and item for later (no output yet).
             self.ss_item = self.samplenum
             self.first = False
-            self.saved_item = self.state
         else:
             # Output the saved item (from the last CLK edge to the current).
             self.es_item = self.samplenum
-            # Output the state we just switched to.
-            self.putx([jtag_states.index(self.state), [self.state]])
+            # Output the old state (from last rising TCK edge to current one).
+            self.putx([jtag_states.index(self.oldstate), [self.oldstate]])
             self.putp(['NEW STATE', self.state])
-            self.ss_item = self.samplenum
-            self.saved_item = self.state
 
-        # If we went from SHIFT-IR to SHIFT-IR, or SHIFT-DR to SHIFT-DR,
-        # collect the current TDI/TDO values (upon rising TCK edge).
-        if self.state.startswith('SHIFT-') and self.oldstate == self.state:
+        # Upon SHIFT-IR/SHIFT-DR collect the current TDI/TDO values.
+        if self.state.startswith('SHIFT-'):
+            if self.first_bit:
+                self.ss_bitstring = self.samplenum
+                self.first_bit = False
+            else:
+                self.putx([16, [str(self.bits_tdi[0])]])
+                self.putx([17, [str(self.bits_tdo[0])]])
+                # Use self.samplenum as ES of the previous bit.
+                self.bits_samplenums_tdi[0][1] = self.samplenum
+                self.bits_samplenums_tdo[0][1] = self.samplenum
+
             self.bits_tdi.insert(0, tdi)
             self.bits_tdo.insert(0, tdo)
-            # TODO: ANN/PROTO output.
-            # self.putx([0, ['TDI add: ' + str(tdi)]])
-            # self.putp([0, ['TDO add: ' + str(tdo)]])
+
+            # Use self.samplenum as SS of the current bit.
+            self.bits_samplenums_tdi.insert(0, [self.samplenum, -1])
+            self.bits_samplenums_tdo.insert(0, [self.samplenum, -1])
 
         # Output all TDI/TDO bits if we just switched from SHIFT-* to EXIT1-*.
         if self.oldstate.startswith('SHIFT-') and \
            self.state.startswith('EXIT1-'):
 
+            self.es_bitstring = self.samplenum
+
             t = self.state[-2:] + ' TDI'
             b = ''.join(map(str, self.bits_tdi))
             h = ' (0x%x' % int('0b' + b, 2) + ')'
             s = t + ': ' + b + h + ', ' + str(len(self.bits_tdi)) + ' bits'
-            # self.putx([0, [s]])
-            # self.putp([t, b])
+            self.putx_bs([18, [s]])
+            self.bits_samplenums_tdi[0][1] = self.samplenum # ES of last bit.
+            self.putp_bs([t, [b, self.bits_samplenums_tdi]])
+            self.putx([16, [str(self.bits_tdi[0])]]) # Last bit.
             self.bits_tdi = []
+            self.bits_samplenums_tdi = []
 
             t = self.state[-2:] + ' TDO'
             b = ''.join(map(str, self.bits_tdo))
             h = ' (0x%x' % int('0b' + b, 2) + ')'
             s = t + ': ' + b + h + ', ' + str(len(self.bits_tdo)) + ' bits'
-            # self.putx([0, [s]])
-            # self.putp([t, b])
+            self.putx_bs([19, [s]])
+            self.bits_samplenums_tdo[0][1] = self.samplenum # ES of last bit.
+            self.putp_bs([t, [b, self.bits_samplenums_tdo]])
+            self.putx([17, [str(self.bits_tdo[0])]]) # Last bit.
             self.bits_tdo = []
+            self.bits_samplenums_tdo = []
+
+            self.first_bit = True
+
+            self.ss_bitstring = self.samplenum
+
+        self.ss_item = self.samplenum
 
     def decode(self, ss, es, data):
         for (self.samplenum, pins) in data:
@@ -210,11 +251,7 @@ class Decoder(srd.Decoder):
             # Store start/end sample for later usage.
             self.ss, self.es = ss, es
 
-            # self.putx([0, ['tdi:%s, tdo:%s, tck:%s, tms:%s' \
-            #                % (tdi, tdo, tck, tms)]])
-
             if (self.oldtck == 0 and tck == 1):
                 self.handle_rising_tck_edge(tdi, tdo, tck, tms)
 
             self.oldtck = tck
-
diff --git a/decoders/jtag_stm32/__init__.py b/decoders/jtag_stm32/__init__.py
index 8a28528..9d60c1c 100644
--- a/decoders/jtag_stm32/__init__.py
+++ b/decoders/jtag_stm32/__init__.py
@@ -27,5 +27,4 @@ https://en.wikipedia.org/wiki/STM32
 http://www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/REFERENCE_MANUAL/CD00171190.pdf (e.g. chapter 31.7: "JTAG debug port")
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/jtag_stm32/pd.py b/decoders/jtag_stm32/pd.py
index 5aac07f..ff5bb77 100644
--- a/decoders/jtag_stm32/pd.py
+++ b/decoders/jtag_stm32/pd.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2015 Uwe Hermann <uwe at hermann-uwe.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
@@ -35,6 +35,23 @@ ir = {
 # ARM Cortex-M3 r1p1-01rel0 ID code
 cm3_idcode = 0x3ba00477
 
+# http://infocenter.arm.com/help/topic/com.arm.doc.ddi0413c/Chdjibcg.html
+cm3_idcode_ver = {
+    0x3: 'JTAG-DP',
+    0x2: 'SW-DP',
+}
+cm3_idcode_part = {
+    0xba00: 'JTAG-DP',
+    0xba10: 'SW-DP',
+}
+
+# http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka14408.html
+jedec_id = {
+    5: {
+        0x3b: 'ARM Ltd.',
+    },
+}
+
 # JTAG ID code in the STM32F10xxx BSC (boundary scan) TAP
 jtag_idcode = {
     0x06412041: 'Low-density device, rev. A',
@@ -74,7 +91,6 @@ apb_ap_reg = {
     0xfc: ['IDR', 'Identification register'],
 }
 
-# TODO: All start/end sample values in self.put() calls are bogus.
 # TODO: Split off generic ARM/Cortex-M3 parts into another protocol decoder?
 
 # Bits[31:28]: Version (here: 0x3)
@@ -82,16 +98,16 @@ apb_ap_reg = {
 # Bits[27:12]: Part number (here: 0xba00)
 #              JTAG-DP: 0xba00, SW-DP: 0xba10
 # Bits[11:1]:  JEDEC (JEP-106) manufacturer ID (here: 0x23b)
-#              Bits[11:8]: Continuation code ('ARM Limited': 0x04)
-#              Bits[7:1]: Identity code ('ARM Limited': 0x3b)
+#              Bits[11:8]: Continuation code ('ARM Ltd.': 0x04)
+#              Bits[7:1]: Identity code ('ARM Ltd.': 0x3b)
 # Bits[0:0]:   Reserved (here: 0x1)
 def decode_device_id_code(bits):
     id_hex = '0x%x' % int('0b' + bits, 2)
-    ver =    '0x%x' % int('0b' + bits[-32:-28], 2)
-    part =   '0x%x' % int('0b' + bits[-28:-12], 2)
-    manuf =  '0x%x' % int('0b' + bits[-12:-1], 2)
-    res =    '0x%x' % int('0b' + bits[-1], 2)
-    return (id_hex, ver, part, manuf, res)
+    ver = cm3_idcode_ver.get(int('0b' + bits[-32:-28], 2), 'UNKNOWN')
+    part = cm3_idcode_part.get(int('0b' + bits[-28:-12], 2), 'UNKNOWN')
+    ids = jedec_id.get(int('0b' + bits[-12:-8], 2) + 1, {})
+    manuf = ids.get(int('0b' + bits[-7:-1], 2), 'UNKNOWN')
+    return (id_hex, manuf, ver, part)
 
 # DPACC is used to access debug port registers (CTRL/STAT, SELECT, RDBUFF).
 # APACC is used to access all Access Port (AHB-AP) registers.
@@ -128,62 +144,88 @@ class Decoder(srd.Decoder):
     inputs = ['jtag']
     outputs = ['jtag_stm32']
     annotations = (
-        ('text', 'Human-readable text'),
+        ('item', 'Item'),
+        ('field', 'Field'),
+        ('command', 'Command'),
+        ('warning', 'Warning'),
+    )
+    annotation_rows = (
+        ('items', 'Items', (0,)),
+        ('fields', 'Fields', (1,)),
+        ('commands', 'Commands', (2,)),
+        ('warnings', 'Warnings', (3,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
-        # self.state = 'BYPASS'
+        self.samplenums = None
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
+    def putx(self, data):
+        self.put(self.ss, self.es, self.out_ann, data)
+
+    def putf(self, s, e, data):
+        self.put(self.samplenums[s][0], self.samplenums[e][1], self.out_ann, data)
+
     def handle_reg_bypass(self, cmd, bits):
-        # TODO
-        self.put(self.ss, self.es, self.out_ann, [0, ['BYPASS: ' + bits]])
+        self.putx([0, ['BYPASS: ' + bits]])
 
     def handle_reg_idcode(self, cmd, bits):
-        # TODO
         # IDCODE is a read-only register which is always accessible.
-        # IR == IDCODE: The device ID code is shifted out via DR next.
-        self.put(self.ss, self.es, self.out_ann,
-                 [0, ['IDCODE: %s (ver=%s, part=%s, manuf=%s, res=%s)' % \
-                 decode_device_id_code(bits)]])
+        # IR == IDCODE: The 32bit device ID code is shifted out via DR next.
+
+        id_hex, manuf, ver, part = decode_device_id_code(bits[:-1])
+        cc = '0x%x' % int('0b' + bits[:-1][-12:-8], 2)
+        ic = '0x%x' % int('0b' + bits[:-1][-7:-1], 2)
+
+        self.putf(0, 0, [1, ['Reserved (BS TAP)', 'BS', 'B']])
+        self.putf(1, 1, [1, ['Reserved', 'Res', 'R']])
+        self.putf(9, 12, [0, ['Continuation code: %s' % cc, 'CC', 'C']])
+        self.putf(2, 8, [0, ['Identity code: %s' % ic, 'IC', 'I']])
+        self.putf(2, 12, [1, ['Manufacturer: %s' % manuf, 'Manuf', 'M']])
+        self.putf(13, 28, [1, ['Part: %s' % part, 'Part', 'P']])
+        self.putf(29, 32, [1, ['Version: %s' % ver, 'Version', 'V']])
+
+        self.ss = self.samplenums[1][0]
+        self.putx([2, ['IDCODE: %s (%s: %s/%s)' % \
+                  decode_device_id_code(bits[:-1])]])
 
     def handle_reg_dpacc(self, cmd, bits):
-        # self.put(self.ss, self.es, self.out_ann,
-        #          [0, ['DPACC/%s: %s' % (cmd, bits)]])
+        bits = bits[:-1]
         s = data_in('DPACC', bits) if (cmd == 'DR TDI') else data_out(bits)
-        self.put(self.ss, self.es, self.out_ann, [0, [s]])
+        self.putx([2, [s]])
 
     def handle_reg_apacc(self, cmd, bits):
-        # self.put(self.ss, self.es, self.out_ann,
-        #          [0, ['APACC/%s: %s' % (cmd, bits)]])
+        bits = bits[:-1]
         s = data_in('APACC', bits) if (cmd == 'DR TDI') else data_out(bits)
-        self.put(self.ss, self.es, self.out_ann, [0, [s]])
+        self.putx([2, [s]])
 
     def handle_reg_abort(self, cmd, bits):
+        bits = bits[:-1]
         # Bits[31:1]: reserved. Bit[0]: DAPABORT.
         a = '' if (bits[0] == '1') else 'No '
         s = 'DAPABORT = %s: %sDAP abort generated' % (bits[0], a)
-        self.put(self.ss, self.es, self.out_ann, [0, [s]])
+        self.putx([2, [s]])
 
         # Warn if DAPABORT[31:1] contains non-zero bits.
         if (bits[:-1] != ('0' * 31)):
-            self.put(self.ss, self.es, self.out_ann,
-                     [0, ['WARNING: DAPABORT[31:1] reserved!']])
+            self.putx([3, ['WARNING: DAPABORT[31:1] reserved!']])
 
     def handle_reg_unknown(self, cmd, bits):
-        self.put(self.ss, self.es, self.out_ann,
-                 [0, ['Unknown instruction: ' % bits]]) # TODO
+        bits = bits[:-1]
+        self.putx([2, ['Unknown instruction: %s' % bits]])
 
     def decode(self, ss, es, data):
-        # Assumption: The right-most char in the 'val' bitstring is the LSB.
         cmd, val = data
 
         self.ss, self.es = ss, es
 
-        # self.put(self.ss, self.es, self.out_ann, [0, [cmd + ' / ' + val]])
+        if cmd != 'NEW STATE':
+            # The right-most char in the 'val' bitstring is the LSB.
+            val, self.samplenums = val
+            self.samplenums.reverse()
 
         # State machine
         if self.state == 'IDLE':
@@ -191,11 +233,15 @@ class Decoder(srd.Decoder):
             if cmd != 'IR TDI':
                 return
             # Switch to the state named after the instruction, or 'UNKNOWN'.
-            # Ignore bits other than IR[3:0]. While the IR register is only
-            # 4 bits in size, some programs (e.g. OpenOCD) might fill in a
-            # few more (dummy) bits. OpenOCD makes IR at least 8 bits long.
-            self.state = ir.get(val[-4:], ['UNKNOWN', 0])[0]
-            self.put(self.ss, self.es, self.out_ann, [0, ['IR: ' + self.state]])
+            # The STM32F10xxx has two serially connected JTAG TAPs, the
+            # boundary scan tap (5 bits) and the Cortex-M3 TAP (4 bits).
+            # See UM 31.5 "STM32F10xxx JTAG TAP connection" for details.
+            self.state = ir.get(val[:-1][-4:], ['UNKNOWN', 0])[0]
+            bstap_ir = ir.get(val[:-1][:4], ['UNKNOWN', 0])[0]
+            self.putf(5, 8, [1, ['IR (BS TAP): ' + bstap_ir]])
+            self.putf(1, 4, [1, ['IR (M3 TAP): ' + self.state]])
+            self.putf(0, 0, [1, ['Reserved (BS TAP)', 'BS', 'B']])
+            self.putx([2, ['IR: %s' % self.state]])
         elif self.state == 'BYPASS':
             # Here we're interested in incoming bits (TDI).
             if cmd != 'DR TDI':
@@ -216,8 +262,5 @@ class Decoder(srd.Decoder):
                 return
             handle_reg = getattr(self, 'handle_reg_%s' % self.state.lower())
             handle_reg(cmd, val)
-            if cmd == 'DR TDO': # TODO: Assumes 'DR TDI' comes before 'DR TDO'
+            if cmd == 'DR TDO': # Assumes 'DR TDI' comes before 'DR TDO'.
                 self.state = 'IDLE'
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/lm75/__init__.py b/decoders/lm75/__init__.py
index d096418..1026df1 100644
--- a/decoders/lm75/__init__.py
+++ b/decoders/lm75/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'i2c' PD and decodes the National LM75
 (and compatibles) temperature sensor protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/lm75/pd.py b/decoders/lm75/pd.py
index 89d6c61..50e3c91 100644
--- a/decoders/lm75/pd.py
+++ b/decoders/lm75/pd.py
@@ -62,7 +62,7 @@ class Decoder(srd.Decoder):
         ('warnings', 'Human-readable warnings'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.reg = 0x00 # Currently selected register
         self.databytes = []
@@ -76,7 +76,7 @@ class Decoder(srd.Decoder):
 
     def putb(self, data):
         # Helper for annotations which span a block of I²C packets.
-        self.put(self.block_start, self.block_end, self.out_ann, data)
+        self.put(self.ss_block, self.es_block, self.out_ann, data)
 
     def warn_upon_invalid_slave(self, addr):
         # LM75 and compatible devices have a 7-bit I²C slave address where
@@ -102,11 +102,11 @@ class Decoder(srd.Decoder):
     def handle_temperature_reg(self, b, s, rw):
         # Common helper for the temperature/T_HYST/T_OS registers.
         if len(self.databytes) == 0:
-            self.block_start = self.ss
+            self.ss_block = self.ss
             self.databytes.append(b)
             return
         self.databytes.append(b)
-        self.block_end = self.es
+        self.es_block = self.es
         self.output_temperature(s, rw)
         self.databytes = []
 
@@ -181,6 +181,3 @@ class Decoder(srd.Decoder):
             else:
                 # self.putx([0, ['Ignoring: %s (data=%s)' % (cmd, databyte)]])
                 pass
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/lpc/__init__.py b/decoders/lpc/__init__.py
index 62a4307..2c2c430 100644
--- a/decoders/lpc/__init__.py
+++ b/decoders/lpc/__init__.py
@@ -23,5 +23,4 @@ LPC (Low-Pin Count) is a protocol for low-bandwidth devices used on
 some PC mainboards, such as the "BIOS chip" or the so-called "Super I/O".
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/lpc/pd.py b/decoders/lpc/pd.py
index 6e03966..9368394 100644
--- a/decoders/lpc/pd.py
+++ b/decoders/lpc/pd.py
@@ -136,7 +136,7 @@ class Decoder(srd.Decoder):
         ('warnings', 'Warnings', (0,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.oldlclk = -1
         self.samplenum = 0
@@ -346,7 +346,7 @@ class Decoder(srd.Decoder):
             if self.state == 'IDLE':
                 # A valid LPC cycle starts with LFRAME# being asserted (low).
                 if lframe != 0:
-                   continue
+                    continue
                 self.ss_block = self.samplenum
                 self.state = 'GET START'
                 self.lad = -1
@@ -365,6 +365,3 @@ class Decoder(srd.Decoder):
                 self.handle_get_data(lad, lad_bits)
             elif self.state == 'GET TAR2':
                 self.handle_get_tar2(lad, lad_bits)
-            else:
-                raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/ir_nec/__init__.py b/decoders/max7219/__init__.py
similarity index 80%
copy from decoders/ir_nec/__init__.py
copy to decoders/max7219/__init__.py
index 84bf428..249f09c 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/max7219/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Paul Evans <leonerd at leonerd.org.uk>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'spi' PD and decodes the Maxim MAX7219 and
+MAX7221 LED matrix driver protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/max7219/pd.py b/decoders/max7219/pd.py
new file mode 100644
index 0000000..c05ff84
--- /dev/null
+++ b/decoders/max7219/pd.py
@@ -0,0 +1,109 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Paul Evans <leonerd at leonerd.org.uk>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import re
+import sigrokdecode as srd
+
+def _decode_intensity(val):
+    intensity = val & 0x0f
+    if intensity == 0:
+        return 'min'
+    elif intensity == 15:
+        return 'max'
+    else:
+        return intensity
+
+registers = {
+    0x00: ['No-op', lambda _: ''],
+    0x09: ['Decode', lambda v: '0b{:08b}'.format(v)],
+    0x0A: ['Intensity', _decode_intensity],
+    0x0B: ['Scan limit', lambda v: 1 + v],
+    0x0C: ['Shutdown', lambda v: 'off' if v else 'on'],
+    0x0F: ['Display test', lambda v: 'on' if v else 'off']
+}
+
+ann_reg, ann_digit, ann_warning = range(3)
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'max7219'
+    name = 'MAX7219'
+    longname = 'Maxim MAX7219/MAX7221'
+    desc = '8-digit LED display driver.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['max7219']
+    annotations = (
+        ('register', 'Registers written to the device'),
+        ('digit', 'Digits displayed on the device'),
+        ('warnings', 'Human-readable warnings'),
+    )
+    annotation_rows = (
+        ('commands', 'Commands', (ann_reg, ann_digit)),
+        ('warnings', 'Warnings', (ann_warning,)),
+    )
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.pos = 0
+        self.cs_start = 0
+
+    def putreg(self, ss, es, reg, value):
+        self.put(ss, es, self.out_ann, [ann_reg, ['%s: %s' % (reg, value)]])
+
+    def putdigit(self, ss, es, digit, value):
+        self.put(ss, es, self.out_ann, [ann_digit, ['Digit %d: %02X' % (digit, value)]])
+
+    def putwarn(self, ss, es, message):
+        self.put(ss, es, self.out_ann, [ann_warning, [message]])
+
+    def decode(self, ss, es, data):
+        ptype, mosi, _ = data
+
+        if ptype == 'DATA':
+            if not self.cs_asserted:
+                return
+
+            if self.pos == 0:
+                self.addr = mosi
+                self.addr_start = ss
+            elif self.pos == 1:
+                if self.addr >= 1 and self.addr <= 8:
+                    self.putdigit(self.addr_start, es, self.addr, mosi)
+                elif self.addr in registers:
+                    name, decoder = registers[self.addr]
+                    self.putreg(self.addr_start, es, name, decoder(mosi))
+                else:
+                    self.putwarn(self.addr_start, es,
+                        'Unknown register %02X' % (self.addr))
+
+            self.pos += 1
+        elif ptype == 'CS-CHANGE':
+            self.cs_asserted = mosi
+            if self.cs_asserted:
+                self.pos = 0
+                self.cs_start = ss
+            else:
+                if self.pos == 1:
+                    # Don't warn if pos=0 so that CS# glitches don't appear
+                    # as spurious warnings.
+                    self.putwarn(self.cs_start, es, 'Short write')
+                elif self.pos > 2:
+                    self.putwarn(self.cs_start, es, 'Overlong write')
diff --git a/decoders/maxim_ds28ea00/__init__.py b/decoders/maxim_ds28ea00/__init__.py
index 34d1d08..049f96a 100644
--- a/decoders/maxim_ds28ea00/__init__.py
+++ b/decoders/maxim_ds28ea00/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'onewire_network' PD and decodes the
 Maxim DS28EA00 1-Wire digital thermometer protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/maxim_ds28ea00/pd.py b/decoders/maxim_ds28ea00/pd.py
index 4693cd9..c7ff7df 100644
--- a/decoders/maxim_ds28ea00/pd.py
+++ b/decoders/maxim_ds28ea00/pd.py
@@ -48,7 +48,7 @@ class Decoder(srd.Decoder):
         ('text', 'Human-readable text'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.trn_beg = 0
         self.trn_end = 0
         self.state = 'ROM'
@@ -88,6 +88,3 @@ class Decoder(srd.Decoder):
                 self.putx([0, ['Temperature conversion status: 0x%02x' % val]])
             elif self.state in [s.upper() for s in command.values()]:
                 self.putx([0, ['TODO \'%s\': 0x%02x' % (self.state, val)]])
-            else:
-                raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/mdio/__init__.py b/decoders/mdio/__init__.py
new file mode 100644
index 0000000..98213b9
--- /dev/null
+++ b/decoders/mdio/__init__.py
@@ -0,0 +1,39 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Elias Oenal <sigrok at eliasoenal.com>
+## All rights reserved.
+##
+## Redistribution and use in source and binary forms, with or without
+## modification, are permitted provided that the following conditions are met:
+##
+## 1. Redistributions of source code must retain the above copyright notice,
+##    this list of conditions and the following disclaimer.
+## 2. Redistributions in binary form must reproduce the above copyright notice,
+##    this list of conditions and the following disclaimer in the documentation
+##    and/or other materials provided with the distribution.
+##
+## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+## POSSIBILITY OF SUCH DAMAGE.
+##
+
+'''
+The MDIO (Management Data Input/Output) protocol decoder supports the
+MII Management serial bus (a bidirectional bus between the PHY and the STA),
+with a clock line (MDC) and a bi-directional data line (MDIO).
+
+MDIO is also known as SMI (Serial Management Interface).
+
+It's part of the Ethernet standard.
+'''
+
+from .pd import Decoder
diff --git a/decoders/mdio/pd.py b/decoders/mdio/pd.py
new file mode 100644
index 0000000..873079a
--- /dev/null
+++ b/decoders/mdio/pd.py
@@ -0,0 +1,330 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Elias Oenal <sigrok at eliasoenal.com>
+## All rights reserved.
+##
+## Redistribution and use in source and binary forms, with or without
+## modification, are permitted provided that the following conditions are met:
+##
+## 1. Redistributions of source code must retain the above copyright notice,
+##    this list of conditions and the following disclaimer.
+## 2. Redistributions in binary form must reproduce the above copyright notice,
+##    this list of conditions and the following disclaimer in the documentation
+##    and/or other materials provided with the distribution.
+##
+## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+## POSSIBILITY OF SUCH DAMAGE.
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'mdio'
+    name = 'MDIO'
+    longname = 'Management Data Input/Output'
+    desc = 'Half-duplex sync serial bus for MII management between MAC and PHY.'
+    license = 'bsd'
+    inputs = ['logic']
+    outputs = ['mdio']
+    channels = (
+        {'id': 'mdc', 'name': 'MDC', 'desc': 'Clock'},
+        {'id': 'mdio', 'name': 'MDIO', 'desc': 'Data'},
+    )
+    options = (
+        {'id': 'show_debug_bits', 'desc': 'Show debug bits',
+            'default': 'no', 'values': ('yes', 'no')},
+    )
+    annotations = (
+        ('bit-val', 'Bit value'),
+        ('bit-num', 'Bit number'),
+        ('frame', 'Frame'),
+        ('frame-idle', 'Bus idle state'),
+        ('frame-error', 'Frame error'),
+        ('decode', 'Decode'),
+    )
+    annotation_rows = (
+        ('bit-val', 'Bit value', (0,)),
+        ('bit-num', 'Bit number', (1,)),
+        ('frame', 'Frame', (2, 3)),
+        ('frame-error', 'Frame error', (4,)),
+        ('decode', 'Decode', (5,)),
+    )
+
+    def __init__(self):
+        self.last_mdc = 1
+        self.illegal_bus = 0
+        self.samplenum = -1
+        self.clause45_addr = -1 # Clause 45 is context sensitive.
+        self.reset_decoder_state()
+
+    def start(self):
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putbit(self, mdio, ss, es):
+        self.put(ss, es, self.out_ann, [0, ['%d' % mdio]])
+        if self.options['show_debug_bits'] == 'yes':
+            self.put(ss, es, self.out_ann, [1, ['%d' % (self.bitcount - 1), '%d' % ((self.bitcount - 1) % 10)]])
+
+    def putff(self, data):
+        self.put(self.ss_frame_field, self.samplenum, self.out_ann, data)
+
+    def putdata(self):
+        self.put(self.ss_frame_field, self.mdiobits[0][2], self.out_ann,
+                 [2, ['DATA: %04X' % self.data, 'DATA', 'D']])
+
+        if self.clause45 and self.opcode == 0:
+            self.clause45_addr = self.data
+
+        # Decode data.
+        if self.opcode > 0 or not self.clause45:
+            decoded_min = ''
+            if self.clause45 and self.clause45_addr != -1:
+                decoded_min += str.format('ADDR: %04X ' % self.clause45_addr)
+            elif self.clause45:
+                decoded_min += str.format('ADDR: UKWN ' % self.clause45_addr)
+
+            if self.clause45 and self.opcode > 1 \
+            or (not self.clause45 and self.opcode):
+                decoded_min += str.format('READ:  %04X' % self.data)
+                is_read = 1
+            else:
+                decoded_min += str.format('WRITE: %04X' % self.data)
+                is_read = 0
+            decoded_ext = str.format(' %s: %02d' % \
+                        ('PRTAD' if self.clause45 else 'PHYAD', self.portad))
+            decoded_ext += str.format(' %s: %02d' % \
+                        ('DEVAD' if self.clause45 else 'REGAD', self.devad))
+            if self.ta_invalid or self.op_invalid:
+                decoded_ext += ' ERROR'
+            self.put(self.ss_frame, self.mdiobits[0][2], self.out_ann,
+                     [5, [decoded_min + decoded_ext, decoded_min]])
+
+            self.put(self.ss_frame, self.mdiobits[0][2], self.out_python,
+                     [(bool(self.clause45), int(self.clause45_addr), \
+                       bool(is_read), int(self.portad), int(self.devad), \
+                       int(self.data))])
+
+        # Post read increment address.
+        if self.clause45 and self.opcode == 2 and self.clause45_addr != -1:
+            self.clause45_addr += 1
+
+    def reset_decoder_state(self):
+        self.mdiobits = []
+        self.bitcount = -1
+        self.opcode = -1
+        self.clause45 = 0
+        self.ss_frame = -1
+        self.ss_frame_field = -1
+        self.preamble_len = 0
+        self.ta_invalid = -1
+        self.op_invalid = ''
+        self.portad = -1
+        self.portad_bits = 5
+        self.devad = -1
+        self.devad_bits = 5
+        self.data = -1
+        self.data_bits = 16
+        self.state = 'PRE'
+
+    def state_PRE(self, mdio):
+        if self.illegal_bus:
+            if mdio == 0:   # Stay in illegal bus state.
+                return
+            else:           # Leave and continue parsing.
+                self.illegal_bus = 0
+                self.put(self.ss_illegal, self.samplenum, self.out_ann,
+                         [4, ['ILLEGAL BUS STATE', 'ILL']])
+                self.ss_frame = self.samplenum
+
+        if self.ss_frame == -1:
+            self.ss_frame = self.samplenum
+
+        if mdio == 1:
+            self.preamble_len += 1
+
+        # Valid MDIO can't clock more than 16 succeeding ones without being
+        # in either IDLE or PRE.
+        if self.preamble_len > 16:
+            if self.preamble_len >= 10000 + 32:
+                self.put(self.ss_frame, self.mdiobits[32][1], self.out_ann,
+                    [3, ['IDLE #%d' % (self.preamble_len - 32), 'IDLE', 'I']])
+                self.ss_frame = self.mdiobits[32][1]
+                self.preamble_len = 32
+                # This is getting out of hand, free some memory.
+                del self.mdiobits[33:-1]
+            if mdio == 0:
+                if self.preamble_len < 32:
+                    self.ss_frame = self.mdiobits[self.preamble_len][1]
+                    self.put(self.ss_frame, self.samplenum, self.out_ann,
+                             [4, ['SHORT PREAMBLE', 'SHRT PRE']])
+                elif self.preamble_len > 32:
+                    self.ss_frame = self.mdiobits[32][1]
+                    self.put(self.mdiobits[self.preamble_len][1],
+                             self.mdiobits[32][1], self.out_ann,
+                             [3, ['IDLE #%d' % (self.preamble_len - 32),
+                             'IDLE', 'I']])
+                    self.preamble_len = 32
+                else:
+                    self.ss_frame = self.mdiobits[32][1]
+                self.put(self.ss_frame, self.samplenum, self.out_ann,
+                         [2, ['PRE #%d' % self.preamble_len, 'PRE', 'P']])
+                self.ss_frame_field = self.samplenum
+                self.state = 'ST'
+        elif mdio == 0:
+                self.ss_illegal = self.ss_frame
+                self.illegal_bus = 1
+
+    def state_ST(self, mdio):
+        if mdio == 0:
+            self.clause45 = 1
+        self.state = 'OP'
+
+    def state_OP(self, mdio):
+        if self.opcode == -1:
+            if self.clause45:
+                st = ['ST (Clause 45)', 'ST 45']
+            else:
+                st = ['ST (Clause 22)', 'ST 22']
+            self.putff([2, st + ['ST', 'S']])
+            self.ss_frame_field = self.samplenum
+
+            if mdio:
+                self.opcode = 2
+            else:
+                self.opcode = 0
+        else:
+            if self.clause45:
+                self.state = 'PRTAD'
+                self.opcode += mdio
+            else:
+                if mdio == self.opcode:
+                    self.op_invalid = 'invalid for Clause 22'
+                self.state = 'PRTAD'
+
+    def state_PRTAD(self, mdio):
+        if self.portad == -1:
+            self.portad = 0
+            if self.clause45:
+                if self.opcode == 0:
+                    op = ['OP: ADDR', 'OP: A']
+                elif self.opcode == 1:
+                    op = ['OP: WRITE', 'OP: W']
+                elif self.opcode == 2:
+                    op = ['OP: READINC', 'OP: RI']
+                elif self.opcode == 3:
+                    op = ['OP: READ', 'OP: R']
+            else:
+                op = ['OP: READ', 'OP: R'] if self.opcode else ['OP: WRITE', 'OP: W']
+            self.putff([2, op + ['OP', 'O']])
+            if self.op_invalid:
+                self.putff([4, ['OP %s' % self.op_invalid, 'OP', 'O']])
+            self.ss_frame_field = self.samplenum
+        self.portad_bits -= 1
+        self.portad |= mdio << self.portad_bits
+        if not self.portad_bits:
+            self.state = 'DEVAD'
+
+    def state_DEVAD(self, mdio):
+        if self.devad == -1:
+            self.devad = 0
+            if self.clause45:
+                prtad = ['PRTAD: %02d' % self.portad, 'PRT', 'P']
+            else:
+                prtad = ['PHYAD: %02d' % self.portad, 'PHY', 'P']
+            self.putff([2, prtad])
+            self.ss_frame_field = self.samplenum
+        self.devad_bits -= 1
+        self.devad |= mdio << self.devad_bits
+        if not self.devad_bits:
+            self.state = 'TA'
+
+    def state_TA(self, mdio):
+        if self.ta_invalid == -1:
+            self.ta_invalid = ''
+            if self.clause45:
+                regad = ['DEVAD: %02d' % self.devad, 'DEV', 'D']
+            else:
+                regad = ['REGAD: %02d' % self.devad, 'REG', 'R']
+            self.putff([2, regad])
+            self.ss_frame_field = self.samplenum
+            if mdio != 1 and ((self.clause45 and self.opcode < 2)
+            or (not self.clause45 and self.opcode == 0)):
+                self.ta_invalid = ' invalid (bit1)'
+        else:
+            if mdio != 0:
+                if self.ta_invalid:
+                    self.ta_invalid = ' invalid (bit1 and bit2)'
+                else:
+                    self.ta_invalid = ' invalid (bit2)'
+            self.state = 'DATA'
+
+    def state_DATA(self, mdio):
+        if self.data == -1:
+            self.data = 0
+            self.putff([2, ['TURNAROUND', 'TA', 'T']])
+            if self.ta_invalid:
+                self.putff([4, ['TURNAROUND%s' % self.ta_invalid,
+                                'TA%s' % self.ta_invalid, 'TA', 'T']])
+            self.ss_frame_field = self.samplenum
+        self.data_bits -= 1
+        self.data |= mdio << self.data_bits
+        if not self.data_bits:
+            # Output final bit.
+            self.mdiobits[0][2] = self.mdiobits[0][1] + self.quartile_cycle_length()
+            self.bitcount += 1
+            self.putbit(self.mdiobits[0][0], self.mdiobits[0][1], self.mdiobits[0][2])
+            self.putdata()
+            self.reset_decoder_state()
+
+    def process_state(self, argument, mdio):
+        method_name = 'state_' + str(argument)
+        method = getattr(self, method_name)
+        return method(mdio)
+
+    # Returns the first quartile point of the frames cycle lengths. This is a
+    # conservative guess for the end of the last cycle. On average it will be
+    # more likely to fall short, than being too long, which makes for better
+    # readability in GUIs.
+    def quartile_cycle_length(self):
+        # 48 is the minimum number of samples we have to have at the end of a
+        # frame. The last sample only has a leading clock edge and is ignored.
+        bitlen = []
+        for i in range(1, 49):
+            bitlen.append(self.mdiobits[i][2] - self.mdiobits[i][1])
+        bitlen = sorted(bitlen)
+        return bitlen[12]
+
+    def handle_bit(self, mdio):
+        self.bitcount += 1
+        self.mdiobits.insert(0, [mdio, self.samplenum, -1])
+
+        if self.bitcount > 0:
+            self.mdiobits[1][2] = self.samplenum # Note end of last cycle.
+            # Output the last bit we processed.
+            self.putbit(self.mdiobits[1][0], self.mdiobits[1][1], self.mdiobits[1][2])
+
+        self.process_state(self.state, mdio)
+
+    def decode(self, ss, es, data):
+        for (self.samplenum, pins) in data:
+            # Ignore identical samples early on (for performance reasons).
+            if self.last_mdc == pins[0]:
+                continue
+            self.last_mdc = pins[0]
+            if pins[0] == 0: # Check for rising edge.
+                continue
+
+            # Found the correct clock edge, now get/handle the bit(s).
+            self.handle_bit(pins[1])
diff --git a/decoders/midi/__init__.py b/decoders/midi/__init__.py
index a453346..4dbcf96 100644
--- a/decoders/midi/__init__.py
+++ b/decoders/midi/__init__.py
@@ -26,5 +26,4 @@ MIDI is layered on top of the UART (async serial) protocol, with a fixed
 baud rate of 31250 baud (+/- 1%) and 8n1 settings. Bytes are sent LSB-first.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/midi/lists.py b/decoders/midi/lists.py
index bc0f9b8..ce4c1ae 100644
--- a/decoders/midi/lists.py
+++ b/decoders/midi/lists.py
@@ -1,7 +1,8 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2013 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2013-2016 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Chris Dreher <chrisdreher at hotmail.com>
 ##
 ## 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
@@ -18,40 +19,41 @@
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
+# Each status byte has 3 string names, each shorter than the previous
 status_bytes = {
     # Channel voice messages
-    0x80: 'note off',
-    0x90: 'note on', # However, velocity = 0 means "note off".
-    0xa0: 'polyphonic key pressure / aftertouch',
-    0xb0: 'control change',
-    0xc0: 'program change',
-    0xd0: 'channel pressure / aftertouch',
-    0xe0: 'pitch bend change',
+    0x80: ['note off', 'note off', 'N off'],
+    0x90: ['note on', 'note on', 'N on'], # However, velocity = 0 means "note off".
+    0xa0: ['polyphonic key pressure / aftertouch', 'key pressure', 'KP' ],
+    0xb0: ['control change', 'ctrl chg', 'CC'],
+    0xc0: ['program change', 'prgm chg', 'PC'],
+    0xd0: ['channel pressure / aftertouch', 'channel pressure', 'CP'],
+    0xe0: ['pitch bend change', 'pitch bend', 'PB'],
 
     # Channel mode messages
     # 0xb0: 'select channel mode', # Note: Same as 'control change'.
 
     # System exclusive messages
-    0xf0: 'system exclusive (SysEx)',
+    0xf0: ['system exclusive', 'SysEx', 'SE'],
 
     # System common messages
-    0xf1: 'MIDI time code quarter frame',
-    0xf2: 'song position pointer',
-    0xf3: 'song select',
-    0xf4: 'undefined',
-    0xf5: 'undefined',
-    0xf6: 'tune request',
-    0xf7: 'end of system exclusive (EOX)',
+    0xf1: ['MIDI time code quarter frame', 'MIDI time code', 'MIDI time'],
+    0xf2: ['song position pointer', 'song position', 'song pos'],
+    0xf3: ['song select', 'song select', 'song sel'],
+    0xf4: ['undefined 0xf4', 'undef 0xf4', 'undef'],
+    0xf5: ['undefined 0xf5', 'undef 0xf5', 'undef'],
+    0xf6: ['tune request', 'tune request', 'tune req'],
+    0xf7: ['end of system exclusive (EOX)', 'end of SysEx', 'EOX'],
 
     # System real time messages
-    0xf8: 'timing clock',
-    0xf9: 'undefined',
-    0xfa: 'start',
-    0xfb: 'continue',
-    0xfc: 'stop',
-    0xfd: 'undefined',
-    0xfe: 'active sensing',
-    0xff: 'system reset',
+    0xf8: ['timing clock', 'timing clock', 'clock'],
+    0xf9: ['undefined 0xf9', 'undef 0xf9', 'undef'],
+    0xfa: ['start', 'start', 's'],
+    0xfb: ['continue', 'continue', 'cont'],
+    0xfc: ['stop', 'stop', 'st'],
+    0xfd: ['undefined 0xfd', 'undef 0xfd', 'undef'],
+    0xfe: ['active sensing', 'active sensing', 'sensing'],
+    0xff: ['system reset', 'reset', 'rst'],
 }
 
 # Universal system exclusive (SysEx) messages, non-realtime (0x7e)
@@ -156,37 +158,37 @@ universal_sysex_realtime = {
 
 # Note: Not all IDs are used/listed, i.e. there are some "holes".
 sysex_manufacturer_ids = {
-    # American group
-    (0x01): 'Sequential',
-    (0x02): 'IDP',
-    (0x03): 'Voyetra/Octave-Plateau',
-    (0x04): 'Moog',
-    (0x05): 'Passport Designs',
-    (0x06): 'Lexicon',
-    (0x07): 'Kurzweil',
-    (0x08): 'Fender',
-    (0x09): 'Gulbransen',
-    (0x0a): 'AKG Acoustics',
-    (0x0b): 'Voyce Music',
-    (0x0c): 'Waveframe Corp',
-    (0x0d): 'ADA Signal Processors',
-    (0x0e): 'Garfield Electronics',
-    (0x0f): 'Ensoniq',
-    (0x10): 'Oberheim',
-    (0x11): 'Apple Computer',
-    (0x12): 'Grey Matter Response',
-    (0x13): 'Digidesign',
-    (0x14): 'Palm Tree Instruments',
-    (0x15): 'JLCooper Electronics',
-    (0x16): 'Lowrey',
-    (0x17): 'Adams-Smith',
-    (0x18): 'Emu Systems',
-    (0x19): 'Harmony Systems',
-    (0x1a): 'ART',
-    (0x1b): 'Baldwin',
-    (0x1c): 'Eventide',
-    (0x1d): 'Inventronics',
-    (0x1f): 'Clarity',
+    # American group (range 01-1f, 000001-001f7f)
+    (0x01,): 'Sequential',
+    (0x02,): 'IDP',
+    (0x03,): 'Voyetra/Octave-Plateau',
+    (0x04,): 'Moog',
+    (0x05,): 'Passport Designs',
+    (0x06,): 'Lexicon',
+    (0x07,): 'Kurzweil',
+    (0x08,): 'Fender',
+    (0x09,): 'Gulbransen',
+    (0x0a,): 'AKG Acoustics',
+    (0x0b,): 'Voyce Music',
+    (0x0c,): 'Waveframe Corp',
+    (0x0d,): 'ADA Signal Processors',
+    (0x0e,): 'Garfield Electronics',
+    (0x0f,): 'Ensoniq',
+    (0x10,): 'Oberheim',
+    (0x11,): 'Apple Computer',
+    (0x12,): 'Grey Matter Response',
+    (0x13,): 'Digidesign',
+    (0x14,): 'Palm Tree Instruments',
+    (0x15,): 'JLCooper Electronics',
+    (0x16,): 'Lowrey',
+    (0x17,): 'Adams-Smith',
+    (0x18,): 'Emu Systems',
+    (0x19,): 'Harmony Systems',
+    (0x1a,): 'ART',
+    (0x1b,): 'Baldwin',
+    (0x1c,): 'Eventide',
+    (0x1d,): 'Inventronics',
+    (0x1f,): 'Clarity',
 
     (0x00, 0x00, 0x01): 'Time Warner Interactive',
     (0x00, 0x00, 0x07): 'Digital Music Corp.',
@@ -267,7 +269,7 @@ sysex_manufacturer_ids = {
     (0x00, 0x00, 0x5c): 'AT&T Bell Labs',
     (0x00, 0x00, 0x5e): 'Symetrix',
     (0x00, 0x00, 0x5f): 'MIDI the World',
-    
+
     (0x00, 0x00, 0x60): 'Desper Products',
     (0x00, 0x00, 0x61): 'Micros\'N MIDI',
     (0x00, 0x00, 0x62): 'Accordians Intl',
@@ -306,32 +308,32 @@ sysex_manufacturer_ids = {
     (0x00, 0x01, 0x02): 'Crystal Semiconductor',
     (0x00, 0x01, 0x03): 'Rockwell Semiconductor',
 
-    # European group
-    (0x20): 'Passac',
-    (0x21): 'SIEL',
-    (0x22): 'Synthaxe',
-    (0x24): 'Hohner',
-    (0x25): 'Twister',
-    (0x26): 'Solton',
-    (0x27): 'Jellinghaus MS',
-    (0x28): 'Southworth Music Systems',
-    (0x29): 'PPG',
-    (0x2a): 'JEN',
-    (0x2b): 'SSL Limited',
-    (0x2c): 'Audio Veritrieb',
-    (0x2f): 'Elka',
-
-    (0x30): 'Dynacord',
-    (0x31): 'Viscount',
-    (0x33): 'Clavia Digital Instruments',
-    (0x34): 'Audio Architecture',
-    (0x35): 'GeneralMusic Corp.',
-    (0x39): 'Soundcraft Electronics',
-    (0x3b): 'Wersi',
-    (0x3c): 'Avab Elektronik Ab',
-    (0x3d): 'Digigram',
-    (0x3e): 'Waldorf Electronics',
-    (0x3f): 'Quasimidi',
+    # European group (range 20-3f, 002000-003f7f)
+    (0x20,): 'Passac',
+    (0x21,): 'SIEL',
+    (0x22,): 'Synthaxe',
+    (0x24,): 'Hohner',
+    (0x25,): 'Twister',
+    (0x26,): 'Solton',
+    (0x27,): 'Jellinghaus MS',
+    (0x28,): 'Southworth Music Systems',
+    (0x29,): 'PPG',
+    (0x2a,): 'JEN',
+    (0x2b,): 'SSL Limited',
+    (0x2c,): 'Audio Veritrieb',
+    (0x2f,): 'Elka',
+
+    (0x30,): 'Dynacord',
+    (0x31,): 'Viscount',
+    (0x33,): 'Clavia Digital Instruments',
+    (0x34,): 'Audio Architecture',
+    (0x35,): 'GeneralMusic Corp.',
+    (0x39,): 'Soundcraft Electronics',
+    (0x3b,): 'Wersi',
+    (0x3c,): 'Avab Elektronik Ab',
+    (0x3d,): 'Digigram',
+    (0x3e,): 'Waldorf Electronics',
+    (0x3f,): 'Quasimidi',
 
     (0x00, 0x20, 0x00): 'Dream',
     (0x00, 0x20, 0x01): 'Strand Lighting',
@@ -378,93 +380,462 @@ sysex_manufacturer_ids = {
     (0x00, 0x20, 0x2d): 'Blue Chip Music Tech',
     (0x00, 0x20, 0x2e): 'BEE OH Corp',
 
-    # Japanese group
-    (0x40): 'Kawai',
-    (0x41): 'Roland',
-    (0x42): 'Korg',
-    (0x43): 'Yamaha',
-    (0x44): 'Casio',
-    (0x46): 'Kamiya Studio',
-    (0x47): 'Akai',
-    (0x48): 'Japan Victor',
-    (0x49): 'Mesosha',
-    (0x4a): 'Hoshino Gakki',
-    (0x4b): 'Fujitsu Elect',
-    (0x4c): 'Sony',
-    (0x4d): 'Nisshin Onpa',
-    (0x4e): 'TEAC',
-    (0x50): 'Matsushita Electric',
-    (0x51): 'Fostex',
-    (0x52): 'Zoom',
-    (0x53): 'Midori Electronics',
-    (0x54): 'Matsushita Communication Industrial',
-    (0x55): 'Suzuki Musical Inst. Mfg.',
+    # Japanese group (range 40-5f, 004000-005f7f)
+    (0x40,): 'Kawai',
+    (0x41,): 'Roland',
+    (0x42,): 'Korg',
+    (0x43,): 'Yamaha',
+    (0x44,): 'Casio',
+    (0x46,): 'Kamiya Studio',
+    (0x47,): 'Akai',
+    (0x48,): 'Japan Victor',
+    (0x49,): 'Mesosha',
+    (0x4a,): 'Hoshino Gakki',
+    (0x4b,): 'Fujitsu Elect',
+    (0x4c,): 'Sony',
+    (0x4d,): 'Nisshin Onpa',
+    (0x4e,): 'TEAC',
+    (0x50,): 'Matsushita Electric',
+    (0x51,): 'Fostex',
+    (0x52,): 'Zoom',
+    (0x53,): 'Midori Electronics',
+    (0x54,): 'Matsushita Communication Industrial',
+    (0x55,): 'Suzuki Musical Inst. Mfg.',
+
+    # Other (range 60-7c, 006000-007f7f)
+
+    # Special (7d-7f)
+    (0x7d,): 'Non-Commercial',
+    (0x7e,): 'Universal Non-Realtime',
+    (0x7f,): 'Universal Realtime',
 }
 
 control_functions = {
-    0x00: 'bank select',
-    0x01: 'modulation wheel/lever',
-    0x02: 'breath controller',
-    # 0x03: undefined
-    0x04: 'foot controller',
-    0x05: 'portamento time',
-    0x06: 'data entry MSB',
-    0x07: 'channel volume (formerly main volume)',
-    0x08: 'balance',
-    # 0x09: undefined
-    0x0a: 'pan',
-    0x0b: 'expression controller',
-    0x0c: 'effect control 1',
-    0x0d: 'effect control 2',
-    # 0x0e-0x0f: undefined
-    0x10: 'general purpose controller 1',
-    0x11: 'general purpose controller 2',
-    0x12: 'general purpose controller 3',
-    0x13: 'general purpose controller 4',
-    # 0x14-0x1f: undefined
-    # 0x20-0x3f: LSB for values 0x00-0x1f
-    0x40: 'damper pedal (sustain)',
-    0x41: 'portamento on/off',
-    0x42: 'sostenuto',
-    0x43: 'soft pedal',
-    0x44: 'legato footswitch', # vv: 00-3f = normal, 40-7f = legato
-    0x45: 'hold 2',
-    0x46: 'sound controller 1 (default: sound variation)',
-    0x47: 'sound controller 2 (default: timbre / harmonic intensity)',
-    0x48: 'sound controller 3 (default: release time)',
-    0x49: 'sound controller 4 (default: attack time)',
-    0x4a: 'sound controller 5 (default: brightness)',
-    0x4b: 'sound controller 6 (GM2 default: decay time)',
-    0x4c: 'sound controller 7 (GM2 default: vibrato rate)',
-    0x4d: 'sound controller 8 (GM2 default: vibrato depth)',
-    0x4e: 'sound controller 9 (GM2 default: vibrato delay)',
-    0x4f: 'sound controller 10',
-    0x50: 'general purpose controller 5',
-    0x51: 'general purpose controller 6',
-    0x52: 'general purpose controller 7',
-    0x53: 'general purpose controller 8',
-    0x54: 'portamento control',
+    0x00: ['bank select MSB', 'bank MSB', 'bank-M'],
+    0x01: ['modulation wheel/lever MSB', 'modulation MSB', 'mod-M'],
+    0x02: ['breath controller MSB', 'breath MSB', 'breath-M'],
+    # 0x03: undefined MSB
+    0x04: ['foot controller MSB', 'foot MSB', 'foot-M'],
+    0x05: ['portamento time MSB', 'portamento MSB', 'porta-M'],
+    0x06: ['data entry MSB', 'data entry MSB', 'data-M'],
+    0x07: ['channel volume MSB (formerly main volume)', 'channel volume MSB', 'ch vol-M'],
+    0x08: ['balance MSB', 'bal MSB', 'bal-M'],
+    # 0x09: undefined MSB
+    0x0a: ['pan MSB', 'pan MSB', 'pan-M'],
+    0x0b: ['expression controller MSB', 'expression MSB', 'expr-M'],
+    0x0c: ['effect control 1 MSB', 'effect 1 MSB', 'eff-1-M'],
+    0x0d: ['effect control 2 MSB', 'effect 2 MSB', 'eff-2-M'],
+    # 0x0e-0x0f: undefined MSB
+    0x10: ['general purpose controller 1 MSB', 'GP ctrl 1 MSB', 'GPC-1-M'],
+    0x11: ['general purpose controller 2 MSB', 'GP ctrl 2 MSB', 'GPC-2-M'],
+    0x12: ['general purpose controller 3 MSB', 'GP ctrl 3 MSB', 'GPC-3-M'],
+    0x13: ['general purpose controller 4 MSB', 'GP ctrl 4 MSB', 'GPC-4-M'],
+    # 0x14-0x1f: undefined MSB
+    0x20: ['bank select LSB', 'bank LSB', 'bank-L'],
+    0x21: ['modulation wheel/lever LSB', 'modulation LSB', 'mod-L'],
+    0x22: ['breath controller LSB', 'breath LSB', 'breath-L'],
+    # 0x23: undefined LSB
+    0x24: ['foot controller LSB', 'foot LSB', 'foot-L'],
+    0x25: ['portamento time LSB', 'portamento LSB', 'porta-L'],
+    0x26: ['data entry LSB', 'data entry LSB', 'data-L'],
+    0x27: ['channel volume LSB (formerly main volume)', 'channel volume LSB', 'ch vol-L'],
+    0x28: ['balance LSB', 'bal LSB', 'bal-L'],
+    # 0x29: undefined LSB
+    0x2a: ['pan LSB', 'pan LSB', 'pan-L'],
+    0x2b: ['expression controller LSB', 'expression LSB', 'expr-L'],
+    0x2c: ['effect control 1 LSB', 'effect 1 LSB', 'eff-1-L'],
+    0x2d: ['effect control 2 LSB', 'effect 2 LSB', 'eff-2-L'],
+    # 0x2e-0x2f: undefined LSB
+    0x30: ['general purpose controller 1 LSB', 'GP ctrl 1 LSB', 'GPC-1-L'],
+    0x31: ['general purpose controller 2 LSB', 'GP ctrl 2 LSB', 'GPC-2-L'],
+    0x32: ['general purpose controller 3 LSB', 'GP ctrl 3 LSB', 'GPC-3-L'],
+    0x33: ['general purpose controller 4 LSB', 'GP ctrl 4 LSB', 'GPC-4-L'],
+    # 0x34-0x3f: undefined LSB
+    0x40: ['damper pedal (sustain)', 'sustain', 'sust'],
+    0x41: ['portamento on/off', 'porta on/off', 'porta on/off'],
+    0x42: ['sostenuto', 'sostenuto', 'sostenuto'],
+    0x43: ['soft pedal', 'soft pedal', 'soft pedal'],
+    0x44: ['legato footswitch', 'legato switch', 'legato'], # vv: 00-3f = normal, 40-7f = legato
+    0x45: ['hold 2', 'hold 2', 'hold 2'],
+    0x46: ['sound controller 1 (default: sound variation)', 'sound ctrl 1', 'snd ctrl 1'],
+    0x47: ['sound controller 2 (default: timbre / harmonic intensity)', 'sound ctrl 2', 'snd ctrl 2'],
+    0x48: ['sound controller 3 (default: release time)', 'sound ctrl 3', 'snd ctrl 3'],
+    0x49: ['sound controller 4 (default: attack time)', 'sound ctrl 4', 'snd ctrl 4'],
+    0x4a: ['sound controller 5 (default: brightness)', 'sound ctrl 5', 'snd ctrl 5'],
+    0x4b: ['sound controller 6 (GM2 default: decay time)', 'sound ctrl 6', 'snd ctrl 6'],
+    0x4c: ['sound controller 7 (GM2 default: vibrato rate)', 'sound ctrl 7', 'snd ctrl 7'],
+    0x4d: ['sound controller 8 (GM2 default: vibrato depth)', 'sound ctrl 8', 'snd ctrl 8'],
+    0x4e: ['sound controller 9 (GM2 default: vibrato delay)', 'sound ctrl 9', 'snd ctrl 9'],
+    0x4f: ['sound controller 10', 'sound ctrl 10', 'snd ctrl 10'],
+    0x50: ['general purpose controller 5', 'GP controller 5', 'GPC-5'],
+    0x51: ['general purpose controller 6', 'GP controller 6', 'GPC-6'],
+    0x52: ['general purpose controller 7', 'GP controller 7', 'GPC-7'],
+    0x53: ['general purpose controller 8', 'GP controller 8', 'GPC-8'],
+    0x54: ['portamento control', 'portamento ctrl', 'porta ctrl'],
     # 0x55-0x5a: undefined
-    0x5b: 'effects 1 depth (formerly external effects depth)',
-    0x5c: 'effects 2 depth (formerly tremolo depth)',
-    0x5d: 'effects 3 depth (formerly chorus depth)',
-    0x5e: 'effects 4 depth (formerly celeste/detune depth)',
-    0x5f: 'effects 5 depth (formerly phaser depth)',
-    0x60: 'data increment',
-    0x61: 'data decrement',
-    0x62: 'non-registered parameter number LSB',
-    0x63: 'non-registered parameter number MSB',
-    0x64: 'registered parameter number LSB',
-    0x65: 'registered parameter number MSB',
+    0x5b: ['effects 1 depth (formerly external effects depth)', 'effects 1 depth', 'eff 1 depth'],
+    0x5c: ['effects 2 depth (formerly tremolo depth)', 'effects 2 depth', 'eff 2 depth'],
+    0x5d: ['effects 3 depth (formerly chorus depth)', 'effects 3 depth', 'eff 3 depth'],
+    0x5e: ['effects 4 depth (formerly celeste/detune depth)', 'effects 4 depth', 'eff 4 depth'],
+    0x5f: ['effects 5 depth (formerly phaser depth)', 'effects 5 depth', 'eff 5 depth'],
+    0x60: ['data increment', 'data inc', 'data++'],
+    0x61: ['data decrement', 'data dec', 'data--'],
+    0x62: ['Non-Registered Parameter Number LSB', 'NRPN LSB', 'NRPN-L'],
+    0x63: ['Non-Registered Parameter Number MSB', 'NRPN MSB', 'NRPN-M'],
+    0x64: ['Registered Parameter Number LSB', 'RPN LSB', 'RPN-L'],
+    0x65: ['Registered Parameter Number MSB', 'RPN MSB', 'RPN-M'],
     # 0x66-0x77: undefined
     # 0x78-0x7f: reserved for channel mode messages
-    0x78: 'all sound off',
-    0x79: 'reset all controllers',
-    0x7a: 'local control on/off',
-    0x7b: 'all notes off',
-    0x7c: 'omni mode off', # all notes off
-    0x7d: 'omni mode on', # all notes off
-    0x7e: 'poly mode off', # mono mode on, all notes off
-    0x7f: 'poly mode on', # mono mode off, all notes off
+    0x78: ['all sound off', 'all snd off', 'snd off'],
+    0x79: ['reset all controllers', 'reset all ctrls', 'reset ctrls'],
+    0x7a: ['local control', 'local ctrl', 'local ctrl'],
+    0x7b: ['all notes off', 'notes off', 'notes off'],
+    0x7c: ['omni mode off', 'omni off', 'omni off'], # all notes off
+    0x7d: ['omni mode on', 'omni on', 'omni on'], # all notes off
+    0x7e: ['mono mode on', 'mono on', 'mono'], # mono mode on, all notes off
+    0x7f: ['poly mode on', 'poly on', 'poly'], # mono mode off, all notes off
+}
+
+gm_instruments = {
+    1:   'Acoustic Grand Piano',
+    2:   'Bright Acoustic Piano',
+    3:   'Electric Grand Piano',
+    4:   'Honky-tonk Piano',
+    5:   'Electric Piano 1',
+    6:   'Electric Piano 2',
+    7:   'Harpsichord',
+    8:   'Clavi',
+    9:   'Celesta',
+    10:  'Glockenspiel',
+    11:  'Music Box',
+    12:  'Vibraphone',
+    13:  'Marimba',
+    14:  'Xylophone',
+    15:  'Tubular Bells',
+    16:  'Dulcimer',
+    17:  'Drawbar Organ',
+    18:  'Percussive Organ',
+    19:  'Rock Organ',
+    20:  'Church Organ',
+    21:  'Reed Organ',
+    22:  'Accordion',
+    23:  'Harmonica',
+    24:  'Tango Accordion',
+    25:  'Acoustic Guitar (nylon)',
+    26:  'Acoustic Guitar (steel)',
+    27:  'Electric Guitar (jazz)',
+    28:  'Electric Guitar (clean)',
+    29:  'Electric Guitar (muted)',
+    30:  'Overdriven Guitar',
+    31:  'Distortion Guitar',
+    32:  'Guitar harmonics',
+    33:  'Acoustic Bass',
+    34:  'Electric Bass (finger)',
+    35:  'Electric Bass (pick)',
+    36:  'Fretless Bass',
+    37:  'Slap Bass 1',
+    38:  'Slap Bass 2',
+    39:  'Synth Bass 1',
+    40:  'Synth Bass 2',
+    41:  'Violin',
+    42:  'Viola',
+    43:  'Cello',
+    44:  'Contrabass',
+    45:  'Tremolo Strings',
+    46:  'Pizzicato Strings',
+    47:  'Orchestral Harp',
+    48:  'Timpani',
+    49:  'String Ensemble 1',
+    50:  'String Ensemble 2',
+    51:  'SynthStrings 1',
+    52:  'SynthStrings 2',
+    53:  'Choir Aahs',
+    54:  'Voice Oohs',
+    55:  'Synth Voice',
+    56:  'Orchestra Hit',
+    57:  'Trumpet',
+    58:  'Trombone',
+    59:  'Tuba',
+    60:  'Muted Trumpet',
+    61:  'French Horn',
+    62:  'Brass Section',
+    63:  'SynthBrass 1',
+    64:  'SynthBrass 2',
+    65:  'Soprano Sax',
+    66:  'Alto Sax',
+    67:  'Tenor Sax',
+    68:  'Baritone Sax',
+    69:  'Oboe',
+    70:  'English Horn',
+    71:  'Bassoon',
+    72:  'Clarinet',
+    73:  'Piccolo',
+    74:  'Flute',
+    75:  'Recorder',
+    76:  'Pan Flute',
+    77:  'Blown Bottle',
+    78:  'Shakuhachi',
+    79:  'Whistle',
+    80:  'Ocarina',
+    81:  'Lead 1 (square)',
+    82:  'Lead 2 (sawtooth)',
+    83:  'Lead 3 (calliope)',
+    84:  'Lead 4 (chiff)',
+    85:  'Lead 5 (charang)',
+    86:  'Lead 6 (voice)',
+    87:  'Lead 7 (fifths)',
+    88:  'Lead 8 (bass + lead)',
+    89:  'Pad 1 (new age)',
+    90:  'Pad 2 (warm)',
+    91:  'Pad 3 (polysynth)',
+    92:  'Pad 4 (choir)',
+    93:  'Pad 5 (bowed)',
+    94:  'Pad 6 (metallic)',
+    95:  'Pad 7 (halo)',
+    96:  'Pad 8 (sweep)',
+    97:  'FX 1 (rain)',
+    98:  'FX 2 (soundtrack)',
+    99:  'FX 3 (crystal)',
+    100: 'FX 4 (atmosphere)',
+    101: 'FX 5 (brightness)',
+    102: 'FX 6 (goblins)',
+    103: 'FX 7 (echoes)',
+    104: 'FX 8 (sci-fi)',
+    105: 'Sitar',
+    106: 'Banjo',
+    107: 'Shamisen',
+    108: 'Koto',
+    109: 'Kalimba',
+    110: 'Bag pipe',
+    111: 'Fiddle',
+    112: 'Shanai',
+    113: 'Tinkle Bell',
+    114: 'Agogo',
+    115: 'Steel Drums',
+    116: 'Woodblock',
+    117: 'Taiko Drum',
+    118: 'Melodic Tom',
+    119: 'Synth Drum',
+    120: 'Reverse Cymbal',
+    121: 'Guitar Fret Noise',
+    122: 'Breath Noise',
+    123: 'Seashore',
+    124: 'Bird Tweet',
+    125: 'Telephone Ring',
+    126: 'Helicopter',
+    127: 'Applause',
+    128: 'Gunshot',
+}
+
+drum_kit = {
+    1:   'GM Standard Kit',
+    9:   'GS Room Kit',
+    17:  'GS Power Kit',
+    25:  'GS Power Kit',
+    26:  'GS TR-808 Kit',
+    33:  'GS Jazz Kit',
+    41:  'GS Brush Kit',
+    49:  'GS Orchestra Kit',
+    57:  'GS Sound FX Kit',
+    128: 'GS CM-64/CM-32 Kit',
+}
+
+# Each quarter frame type has 2 string names, each shorter than the previous
+quarter_frame_type = {
+    0: ['frame count LS nibble', 'frame LSN'],
+    1: ['frame count MS nibble', 'frame MSN'],
+    2: ['seconds LS nibble', 'sec LSN'],
+    3: ['seconds MS nibble', 'sec MSN'],
+    4: ['minutes LS nibble', 'min LSN'],
+    5: ['minutes MS nibble', 'min MSN'],
+    6: ['hours LS nibble', 'hrs LSN'],
+    7: ['hours MS nibble and SMPTE type', 'hrs MSN'],
+}
+
+smpte_type = {
+    0: '24 fps',
+    1: '25 fps',
+    2: '30 fps (drop-frame)',
+    3: '30 fps (non-drop)',
 }
 
+chromatic_notes = {
+    0: 'C-1',
+    1: 'C#-1',
+    2: 'D-1',
+    3: 'D#-1',
+    4: 'E-1',
+    5: 'F-1',
+    6: 'F#-1',
+    7: 'G-1',
+    8: 'G#-1',
+    9: 'A-1',
+    10: 'A#-1',
+    11: 'B-1',
+    12: 'C0',
+    13: 'C#0',
+    14: 'D0',
+    15: 'D#0',
+    16: 'E0',
+    17: 'F0',
+    18: 'F#0',
+    19: 'G0',
+    20: 'G#0',
+    21: 'A0',
+    22: 'A#0',
+    23: 'B0',
+    24: 'C1',
+    25: 'C#1',
+    26: 'D1',
+    27: 'D#1',
+    28: 'E1',
+    29: 'F1',
+    30: 'F#1',
+    31: 'G1',
+    32: 'G#1',
+    33: 'A1',
+    34: 'A#1',
+    35: 'B1',
+    36: 'C2',
+    37: 'C#2',
+    38: 'D2',
+    39: 'D#2',
+    40: 'E2',
+    41: 'F2',
+    42: 'F#2',
+    43: 'G2',
+    44: 'G#2',
+    45: 'A2',
+    46: 'A#2',
+    47: 'B2',
+    48: 'C3',
+    49: 'C#3',
+    50: 'D3',
+    51: 'D#3',
+    52: 'E3',
+    53: 'F3',
+    54: 'F#3',
+    55: 'G3',
+    56: 'G#3',
+    57: 'A3',
+    58: 'A#3',
+    59: 'B3',
+    60: 'C4',
+    61: 'C#4',
+    62: 'D4',
+    63: 'D#4',
+    64: 'E4',
+    65: 'F4',
+    66: 'F#4',
+    67: 'G4',
+    68: 'G#4',
+    69: 'A4',
+    70: 'A#4',
+    71: 'B4',
+    72: 'C5',
+    73: 'C#5',
+    74: 'D5',
+    75: 'D#5',
+    76: 'E5',
+    77: 'F5',
+    78: 'F#5',
+    79: 'G5',
+    80: 'G#5',
+    81: 'A5',
+    82: 'A#5',
+    83: 'B5',
+    84: 'C6',
+    85: 'C#6',
+    86: 'D6',
+    87: 'D#6',
+    88: 'E6',
+    89: 'F6',
+    90: 'F#6',
+    91: 'G6',
+    92: 'G#6',
+    93: 'A6',
+    94: 'A#6',
+    95: 'B6',
+    96: 'C7',
+    97: 'C#7',
+    98: 'D7',
+    99: 'D#7',
+    100: 'E7',
+    101: 'F7',
+    102: 'F#7',
+    103: 'G7',
+    104: 'G#7',
+    105: 'A7',
+    106: 'A#7',
+    107: 'B7',
+    108: 'C8',
+    109: 'C#8',
+    110: 'D8',
+    111: 'D#8',
+    112: 'E8',
+    113: 'F8',
+    114: 'F#8',
+    115: 'G8',
+    116: 'G#8',
+    117: 'A8',
+    118: 'A#8',
+    119: 'B8',
+    120: 'C9',
+    121: 'C#9',
+    122: 'D9',
+    123: 'D#9',
+    124: 'E9',
+    125: 'F9',
+    126: 'F#9',
+    127: 'G9',
+}
+
+percussion_notes = {
+    35: 'Acoustic Bass Drum',
+    36: 'Bass Drum 1',
+    37: 'Side Stick',
+    38: 'Acoustic Snare',
+    39: 'Hand Clap',
+    40: 'Electric Snare',
+    41: 'Low Floor Tom',
+    42: 'Closed Hi Hat',
+    43: 'High Floor Tom',
+    44: 'Pedal Hi-Hat',
+    45: 'Low Tom',
+    46: 'Open Hi-Hat',
+    47: 'Low-Mid Tom',
+    48: 'Hi Mid Tom',
+    49: 'Crash Cymbal 1',
+    50: 'High Tom',
+    51: 'Ride Cymbal 1',
+    52: 'Chinese Cymbal',
+    53: 'Ride Bell',
+    54: 'Tambourine',
+    55: 'Splash Cymbal',
+    56: 'Cowbell',
+    57: 'Crash Cymbal 2',
+    58: 'Vibraslap',
+    59: 'Ride Cymbal 2',
+    60: 'Hi Bongo',
+    61: 'Low Bongo',
+    62: 'Mute Hi Conga',
+    63: 'Open Hi Conga',
+    64: 'Low Conga',
+    65: 'High Timbale',
+    66: 'Low Timbale',
+    67: 'High Agogo',
+    68: 'Low Agogo',
+    69: 'Cabasa',
+    70: 'Maracas',
+    71: 'Short Whistle',
+    72: 'Long Whistle',
+    73: 'Short Guiro',
+    74: 'Long Guiro',
+    75: 'Claves',
+    76: 'Hi Wood Block',
+    77: 'Low Wood Block',
+    78: 'Mute Cuica',
+    79: 'Open Cuica',
+    80: 'Mute Triangle',
+    81: 'Open Triangle',
+}
diff --git a/decoders/midi/pd.py b/decoders/midi/pd.py
index b1f0053..18c439f 100644
--- a/decoders/midi/pd.py
+++ b/decoders/midi/pd.py
@@ -1,7 +1,8 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2013 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2013-2016 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Chris Dreher <chrisdreher at hotmail.com> 
 ##
 ## 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
@@ -35,11 +36,19 @@ class Decoder(srd.Decoder):
     outputs = ['midi']
     annotations = (
         ('text-verbose', 'Human-readable text (verbose)'),
+        ('text-sysreal-verbose', 'Human-readable SysReal text (verbose)'),
+        ('text-error', 'Human-readable Error text'),
+    )
+    annotation_rows = (
+        ('normal', 'Normal', (0, 2)),
+        ('sys-real', 'SysReal', (1,)),
     )
 
-    def __init__(self, **kwargs):
-        self.cmd = []
+    def __init__(self):
         self.state = 'IDLE'
+        self.status_byte = 0
+        self.explicit_status_byte = False
+        self.cmd = []
         self.ss = None
         self.es = None
         self.ss_block = None
@@ -51,161 +60,565 @@ class Decoder(srd.Decoder):
     def putx(self, data):
         self.put(self.ss_block, self.es_block, self.out_ann, data)
 
-    def handle_channel_msg_0x80(self):
+    def get_note_name(self, channel, note):
+        if channel != 10:
+            return chromatic_notes[note]
+        else:
+            return 'assuming ' + percussion_notes.get(note, 'undefined')
+
+    def check_for_garbage_flush(self, is_flushed):
+        if is_flushed:
+            if self.explicit_status_byte:
+                self.cmd.insert(0, self.status_byte)
+            self.handle_garbage_msg(None)
+
+    def soft_clear_status_byte(self):
+        self.explicit_status_byte = False
+
+    def hard_clear_status_byte(self):
+        self.status_byte = 0
+        self.explicit_status_byte = False
+
+    def set_status_byte(self, newbyte):
+        self.status_byte = newbyte
+        self.explicit_status_byte = True
+
+    def handle_channel_msg_0x80(self, is_flushed):
         # Note off: 8n kk vv
         # n = channel, kk = note, vv = velocity
         c = self.cmd
-        if len(c) < 3:
+        if len(c) < 2:
+            self.check_for_garbage_flush(is_flushed)
             return
         self.es_block = self.es
-        msg, chan, note, velocity = c[0] & 0xf0, (c[0] & 0x0f) + 1, c[1], c[2]
-        self.putx([0, ['Channel %d: %s (note = %d, velocity = %d)' % \
-                  (chan, status_bytes[msg], note, velocity)]])
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        note, velocity = c[0], c[1]
+        note_name = self.get_note_name(chan, note)
+        self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
+                  (chan, status_bytes[msg][0], note, note_name, velocity),
+                  'ch %d: %s %d, velocity = %d' % \
+                  (chan, status_bytes[msg][1], note, velocity),
+                  '%d: %s %d, vel %d' % \
+                  (chan, status_bytes[msg][2], note, velocity)]])
         self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_0x90(self):
+    def handle_channel_msg_0x90(self, is_flushed):
         # Note on: 9n kk vv
         # n = channel, kk = note, vv = velocity
         # If velocity == 0 that actually means 'note off', though.
         c = self.cmd
-        if len(c) < 3:
+        if len(c) < 2:
+            self.check_for_garbage_flush(is_flushed)
             return
-        self.es_block = self.ss
-        msg, chan, note, velocity = c[0] & 0xf0, (c[0] & 0x0f) + 1, c[1], c[2]
-        s = 'note off' if (velocity == 0) else status_bytes[msg]
-        self.putx([0, ['Channel %d: %s (note = %d, velocity = %d)' % \
-                  (chan, s, note, velocity)]])
+        self.es_block = self.es
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        note, velocity = c[0], c[1]
+        s = status_bytes[0x80] if (velocity == 0) else status_bytes[msg]
+        note_name = self.get_note_name(chan, note)
+        self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
+                  (chan, s[0], note, note_name, velocity),
+                  'ch %d: %s %d, velocity = %d' % \
+                  (chan, s[1], note, velocity),
+                  '%d: %s %d, vel %d' % \
+                  (chan, s[2], note, velocity)]])
         self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_0xa0(self):
+    def handle_channel_msg_0xa0(self, is_flushed):
         # Polyphonic key pressure / aftertouch: An kk vv
         # n = channel, kk = polyphonic key pressure, vv = pressure value
-        pass # TODO
+        c = self.cmd
+        if len(c) < 2:
+            self.check_for_garbage_flush(is_flushed)
+            return
+        self.es_block = self.es
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        note, pressure = c[0], c[1]
+        note_name = self.get_note_name(chan, note)
+        self.putx([0, ['Channel %d: %s of %d for note = %d \'%s\'' % \
+                  (chan, status_bytes[msg][0], pressure, note, note_name),
+                  'ch %d: %s %d for note %d' % \
+                  (chan, status_bytes[msg][1], pressure, note),
+                  '%d: %s %d, N %d' % \
+                  (chan, status_bytes[msg][2], pressure, note)]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
     def handle_controller_0x44(self):
         # Legato footswitch: Bn 44 vv
         # n = channel, vv = value (<= 0x3f: normal, > 0x3f: legato)
-        chan, vv = (self.cmd[0] & 0x0f) + 1, self.cmd[2]
-        t = 'normal' if vv <= 0x3f else 'legato'
-        self.putx([0, ['Channel %d: control function \'%s\' = %s' % \
-                  (chan, control_functions[0x44], t)]])
+        c = self.cmd
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        vv = c[1]
+        t = ('normal', 'no') if vv <= 0x3f else ('legato', 'yes')
+        self.putx([0, ['Channel %d: %s \'%s\' = %s' % \
+                  (chan, status_bytes[msg][0],
+                  control_functions[0x44][0], t[0]),
+                  'ch %d: %s \'%s\' = %s' % \
+                  (chan, status_bytes[msg][1],
+                  control_functions[0x44][1], t[0]),
+                  '%d: %s \'%s\' = %s' % \
+                  (chan, status_bytes[msg][2],
+                  control_functions[0x44][2], t[1])]])
 
     def handle_controller_0x54(self):
         # Portamento control (PTC): Bn 54 kk
         # n = channel, kk = source note for pitch reference
-        chan, kk = (self.cmd[0] & 0x0f) + 1, self.cmd[2]
-        self.putx([0, ['Channel %d: control function \'%s\' (source note ' \
-                  '= %d)' % (chan, control_functions[0x54], kk)]])
+        c = self.cmd
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        kk = c[1]
+        kk_name = self.get_note_name(chan, kk)
+        self.putx([0, ['Channel %d: %s \'%s\' (source note = %d / %s)' % \
+                  (chan, status_bytes[msg][0],
+                  control_functions[0x54][0], kk, kk_name),
+                  'ch %d: %s \'%s\' (source note = %d)' % \
+                  (chan, status_bytes[msg][1],
+                  control_functions[0x54][1], kk),
+                  '%d: %s \'%s\' (src N %d)' % \
+                  (chan, status_bytes[msg][2],
+                  control_functions[0x54][2], kk)]])
 
     def handle_controller_generic(self):
         c = self.cmd
-        chan, fn, param = (c[0] & 0x0f) + 1, c[1], c[2]
-        ctrl_fn = control_functions.get(fn, 'undefined')
-        self.putx([0, ['Channel %d: control change to function \'%s\' ' \
-                  '(param = 0x%02x)' % (chan, ctrl_fn, param)]])
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        fn, param = c[0], c[1]
+        default_name = 'undefined'
+        ctrl_fn = control_functions.get(fn, default_name)
+        if ctrl_fn == default_name:
+            ctrl_fn = ('undefined 0x%02x' % fn, 'undef 0x%02x' % fn, '0x%02x' % fn)
+        self.putx([0, ['Channel %d: %s \'%s\' (param = 0x%02x)' % \
+                  (chan, status_bytes[msg][0], ctrl_fn[0], param),
+                  'ch %d: %s \'%s\' (param = 0x%02x)' % \
+                  (chan, status_bytes[msg][1], ctrl_fn[1], param),
+                  '%d: %s \'%s\' is 0x%02x' % \
+                  (chan, status_bytes[msg][2], ctrl_fn[2], param)]])
 
-    def handle_channel_msg_0xb0(self):
+    def handle_channel_mode(self):
+        # Channel Mode: Bn mm vv
+        # n = channel, mm = mode number (120 - 127), vv = value
+        c = self.cmd
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        mm, vv = c[0], c[1]
+        mode_fn = control_functions.get(mm, ('undefined', 'undef', 'undef'))
+        # Decode the value based on the mode number.
+        vv_string = ('', '')
+        if mm == 122:           # mode = local control?
+            if vv == 0:
+                vv_string = ('off', 'off')
+            elif vv == 127:     # mode = poly mode on?
+                vv_string = ('on', 'on')
+            else:
+                vv_string = ('(non-standard param value of 0x%02x)' % vv,
+                            '0x%02x' % vv)
+        elif mm == 126:         # mode = mono mode on?
+            if vv != 0:
+                vv_string = ('(%d channels)' % vv, '(%d ch)' % vv)
+            else:
+                vv_string = ('(channels \'basic\' through 16)',
+                            '(ch \'basic\' thru 16)')
+        elif vv != 0: # All other channel mode messages expect vv == 0.
+            vv_string = ('(non-standard param value of 0x%02x)' % vv,
+                        '0x%02x' % vv)
+        self.putx([0, ['Channel %d: %s \'%s\' %s' % \
+                      (chan, status_bytes[msg][0], mode_fn[0], vv_string[0]),
+                      'ch %d: %s \'%s\' %s' % \
+                      (chan, status_bytes[msg][1], mode_fn[1], vv_string[1]),
+                      '%d: %s \'%s\' %s' % \
+                      (chan, status_bytes[msg][2], mode_fn[2], vv_string[1])]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
+
+    def handle_channel_msg_0xb0(self, is_flushed):
         # Control change (or channel mode messages): Bn cc vv
         # n = channel, cc = control number (0 - 119), vv = control value
         c = self.cmd
-        if (len(c) >= 2) and (c[1] in range(0x78, 0x7f + 1)):
-            # This is not a control change, but rather a channel mode message.
-            # TODO: Handle channel mode messages.
-            return
-        if len(c) < 3:
+        if len(c) < 2:
+            self.check_for_garbage_flush(is_flushed)
             return
         self.es_block = self.es
-        handle_ctrl = getattr(self, 'handle_controller_0x%02x' % c[1],
+        if c[0] in range(0x78, 0x7f + 1):
+            self.handle_channel_mode()
+            return
+        handle_ctrl = getattr(self, 'handle_controller_0x%02x' % c[0],
                               self.handle_controller_generic)
         handle_ctrl()
         self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_0xc0(self):
+    def handle_channel_msg_0xc0(self, is_flushed):
         # Program change: Cn pp
         # n = channel, pp = program number (0 - 127)
-        pass # TODO
+        c = self.cmd
+        if len(c) < 1:
+            self.check_for_garbage_flush(is_flushed)
+            return
+        self.es_block = self.es
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        pp = self.cmd[0] + 1
+        change_type = 'instrument'
+        name = ''
+        if chan != 10:  # channel != percussion
+            name = gm_instruments.get(pp, 'undefined')
+        else:
+            change_type = 'drum kit'
+            name = drum_kit.get(pp, 'undefined')
+        self.putx([0, ['Channel %d: %s to %s %d (assuming %s)' % \
+            (chan, status_bytes[msg][0], change_type, pp, name),
+            'ch %d: %s to %s %d' % \
+            (chan, status_bytes[msg][1], change_type, pp),
+            '%d: %s %d' % \
+            (chan, status_bytes[msg][2], pp)]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_0xd0(self):
+    def handle_channel_msg_0xd0(self, is_flushed):
         # Channel pressure / aftertouch: Dn vv
         # n = channel, vv = pressure value
-        pass # TODO
+        c = self.cmd
+        if len(c) < 1:
+            self.check_for_garbage_flush(is_flushed)
+            return
+        self.es_block = self.es
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        vv = self.cmd[0]
+        self.putx([0, ['Channel %d: %s %d' % (chan, status_bytes[msg][0], vv),
+                      'ch %d: %s %d' % (chan, status_bytes[msg][1], vv),
+                      '%d: %s %d' % (chan, status_bytes[msg][2], vv)]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_0xe0(self):
+    def handle_channel_msg_0xe0(self, is_flushed):
         # Pitch bend change: En ll mm
         # n = channel, ll = pitch bend change LSB, mm = pitch bend change MSB
-        pass # TODO
+        c = self.cmd
+        if len(c) < 2:
+            self.check_for_garbage_flush(is_flushed)
+            return
+        self.es_block = self.es
+        msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
+        ll, mm = self.cmd[0], self.cmd[1]
+        decimal = (mm << 7) + ll
+        self.putx([0, ['Channel %d: %s 0x%02x 0x%02x (%d)' % \
+                      (chan, status_bytes[msg][0], ll, mm, decimal),
+                      'ch %d: %s 0x%02x 0x%02x (%d)' % \
+                      (chan, status_bytes[msg][1], ll, mm, decimal),
+                      '%d: %s (%d)' % \
+                      (chan, status_bytes[msg][2], decimal)]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
-    def handle_channel_msg_generic(self):
-        msg_type = self.cmd[0] & 0xf0
-        self.putx([0, ['Unknown channel message type: 0x%02x' % msg_type]])
-        # TODO: Handle properly.
+    def handle_channel_msg_generic(self, is_flushed):
+        # TODO: It should not be possible to hit this code.
+        # It currently can not be unit tested.
+        msg_type = self.status_byte & 0xf0
+        self.es_block = self.es
+        self.putx([2, ['Unknown channel message type: 0x%02x' % msg_type]])
+        self.cmd, self.state = [], 'IDLE'
+        self.soft_clear_status_byte()
 
     def handle_channel_msg(self, newbyte):
-        self.cmd.append(newbyte)
-        msg_type = self.cmd[0] & 0xf0
+        if newbyte is not None:
+            if newbyte >= 0x80:
+                self.set_status_byte(newbyte)
+            else:
+                self.cmd.append(newbyte)
+        msg_type = self.status_byte & 0xf0
         handle_msg = getattr(self, 'handle_channel_msg_0x%02x' % msg_type,
                              self.handle_channel_msg_generic)
-        handle_msg()
+        handle_msg(newbyte is None)
 
     def handle_sysex_msg(self, newbyte):
-        # SysEx message: 1 status byte, x data bytes, EOX byte
-        self.cmd.append(newbyte)
-        if newbyte != 0xf7: # EOX
+        # SysEx message: 1 status byte, 1-3 manuf. bytes, x data bytes, EOX byte
+        #
+        # SysEx messages are variable length, can be terminated by EOX or
+        # by any non-SysReal status byte, and it clears self.status_byte.
+        #
+        # Note: All System message codes don't utilize self.status_byte.
+        self.hard_clear_status_byte()
+        if newbyte != 0xf7 and newbyte is not None: # EOX
+            self.cmd.append(newbyte)
             return
         self.es_block = self.es
-        # TODO: Get message ID, vendor ID, message contents, etc.
-        self.putx([0, ['SysEx message']])
+        # Note: Unlike other methods, this code pops bytes out of self.cmd
+        # to isolate the data.
+        msg = self.cmd.pop(0)
+        if len(self.cmd) < 1:
+            self.putx([2, ['%s: truncated manufacturer code (<1 bytes)' % \
+                          status_bytes[msg][0],
+                          '%s: truncated manufacturer (<1 bytes)' % \
+                          status_bytes[msg][1],
+                          '%s: trunc. manu.' % status_bytes[msg][2]]])
+            self.cmd, self.state = [], 'IDLE'
+            return
+        # Extract the manufacturer name (or SysEx realtime or non-realtime).
+        m1 = self.cmd.pop(0)
+        manu = (m1,)
+        if m1 == 0x00:  # If byte == 0, then 2 more manufacturer bytes follow.
+            if len(self.cmd) < 2:
+                self.putx([2, ['%s: truncated manufacturer code (<3 bytes)' % \
+                          status_bytes[msg][0],
+                          '%s: truncated manufacturer (<3 bytes)' % \
+                          status_bytes[msg][1],
+                          '%s: trunc. manu.' % status_bytes[msg][2]]])
+                self.cmd, self.state = [], 'IDLE'
+                return
+            manu = (m1, self.cmd.pop(0), self.cmd.pop(0))
+        default_name = 'undefined'
+        manu_name = sysex_manufacturer_ids.get(manu, default_name)
+        if manu_name == default_name:
+            if len(manu) == 3:
+                manu_name = ('%s (0x%02x 0x%02x 0x%02x)' % \
+                            (default_name, manu[0], manu[1], manu[2]),
+                            default_name)
+            else:
+                manu_name = ('%s (0x%02x)' % (default_name, manu[0]),
+                            default_name)
+        else:
+            manu_name = (manu_name, manu_name)
+        # Extract the payload, display in 1 of 2 formats
+        # TODO: Write methods to decode SysEx realtime & non-realtime payloads.
+        payload0 = ''
+        payload1 = ''
+        while len(self.cmd) > 0:
+            byte = self.cmd.pop(0)
+            payload0 += '0x%02x ' % (byte)
+            payload1 += '%02x ' % (byte)
+        if payload0 == '':
+            payload0 = '<empty>'
+            payload1 = '<>'
+        payload = (payload0, payload1)
+        self.putx([0, ['%s: for \'%s\' with payload %s' % \
+                      (status_bytes[msg][0], manu_name[0], payload[0]),
+                      '%s: \'%s\', payload %s' % \
+                      (status_bytes[msg][1], manu_name[1], payload[1]),
+                      '%s: \'%s\', payload %s' % \
+                      (status_bytes[msg][2], manu_name[1], payload[1])]])
+        self.cmd, self.state = [], 'IDLE'
+
+    def handle_syscommon_midi_time_code_quarter_frame_msg(self, newbyte):
+        # MIDI time code quarter frame: F1 nd
+        # n = message type
+        # d = values
+        #
+        # Note: All System message codes don't utilize self.status_byte,
+        # and System Exclusive and System Common clear it.
+        c = self.cmd
+        if len(c) < 2:
+            if newbyte is None:
+                self.handle_garbage_msg(None)
+            return
+        msg = c[0]
+        nn, dd = (c[1] & 0x70) >> 4, c[1] & 0x0f
+        group = ('System Common', 'SysCom', 'SC')
+        self.es_block = self.es
+        if nn != 7: # If message type does not contain SMPTE type.
+            self.putx([0, ['%s: %s of %s, value 0x%01x' % \
+                          (group[0], status_bytes[msg][0],
+                          quarter_frame_type[nn][0], dd),
+                          '%s: %s of %s, value 0x%01x' % \
+                          (group[1], status_bytes[msg][1],
+                          quarter_frame_type[nn][1], dd),
+                          '%s: %s of %s, value 0x%01x' % \
+                          (group[2], status_bytes[msg][2],
+                          quarter_frame_type[nn][1], dd)]])
+            self.cmd, self.state = [], 'IDLE'
+            return
+        tt = (dd & 0x6) >> 1
+        self.putx([0, ['%s: %s of %s, value 0x%01x for %s' % \
+                      (group[0], status_bytes[msg][0], \
+                      quarter_frame_type[nn][0], dd, smpte_type[tt]),
+                      '%s: %s of %s, value 0x%01x for %s' % \
+                      (group[1], status_bytes[msg][1], \
+                      quarter_frame_type[nn][1], dd, smpte_type[tt]),
+                      '%s: %s of %s, value 0x%01x for %s' % \
+                      (group[2], status_bytes[msg][2], \
+                      quarter_frame_type[nn][1], dd, smpte_type[tt])]])
         self.cmd, self.state = [], 'IDLE'
 
     def handle_syscommon_msg(self, newbyte):
-        pass # TODO
+        # System common messages
+        #
+        # There are 5 simple formats (which are directly handled here) and
+        # 1 complex one called MIDI time code quarter frame.
+        #
+        # Note: While the MIDI lists 0xf7 as a "system common" message, it
+        # is actually only used with SysEx messages so it is processed there.
+        #
+        # Note: All System message codes don't utilize self.status_byte.
+        self.hard_clear_status_byte()
+        if newbyte is not None:
+            self.cmd.append(newbyte)
+        c = self.cmd
+        msg = c[0]
+        group = ('System Common', 'SysCom', 'SC')
+        if msg == 0xf1:
+            # MIDI time code quarter frame
+            self.handle_syscommon_midi_time_code_quarter_frame_msg(newbyte)
+            return
+        elif msg == 0xf2:
+            # Song position pointer: F2 ll mm
+            # ll = LSB position, mm = MSB position
+            if len(c) < 3:
+                if newbyte is None:
+                    self.handle_garbage_msg(None)
+                return
+            ll, mm = c[1], c[2]
+            decimal = (mm << 7) + ll
+            self.es_block = self.es
+            self.putx([0, ['%s: %s 0x%02x 0x%02x (%d)' % \
+                          (group[0], status_bytes[msg][0], ll, mm, decimal),
+                          '%s: %s 0x%02x 0x%02x (%d)' % \
+                          (group[1], status_bytes[msg][1], ll, mm, decimal),
+                          '%s: %s (%d)' % \
+                          (group[2], status_bytes[msg][2], decimal)]])
+        elif msg == 0xf3:
+            # Song select: F3 ss
+            # ss = song selection number
+            if len(c) < 2:
+                if newbyte is None:
+                    self.handle_garbage_msg(None)
+                return
+            ss = c[1]
+            self.es_block = self.es
+            self.putx([0, ['%s: %s number %d' % \
+                          (group[0], status_bytes[msg][0], ss),
+                          '%s: %s number %d' % \
+                          (group[1], status_bytes[msg][1], ss),
+                          '%s: %s # %d' % \
+                          (group[2], status_bytes[msg][2], ss)]])
+        elif msg == 0xf4 or msg == 0xf5 or msg == 0xf6:
+            # Undefined 0xf4, Undefined 0xf5, and Tune Request (respectively).
+            # All are only 1 byte long with no data bytes.
+            self.es_block = self.es
+            self.putx([0, ['%s: %s' % (group[0], status_bytes[msg][0]),
+                          '%s: %s' % (group[1], status_bytes[msg][1]),
+                          '%s: %s' % (group[2], status_bytes[msg][2])]])
+        self.cmd, self.state = [], 'IDLE'
 
     def handle_sysrealtime_msg(self, newbyte):
         # System realtime message: 0b11111ttt (t = message type)
-        self.es_block = self.ss
-        self.putx([0, ['System realtime message: %s' % status_bytes[newbyte]]])
+        #
+        # Important: These messages are handled differently from all others
+        # because they are allowed to temporarily interrupt other messages.
+        # The interrupted messages resume after the realtime message is done.
+        # Thus, they mostly leave 'self' the way it was found.
+        #
+        # Note: All System message codes don't utilize self.status_byte.
+        old_ss_block, old_es_block = self.ss_block, self.es_block
+        self.ss_block, self.es_block = self.ss, self.es
+        group = ('System Realtime', 'SysReal', 'SR')
+        self.putx([1, ['%s: %s' % (group[0], status_bytes[newbyte][0]),
+                      '%s: %s' % (group[1], status_bytes[newbyte][1]),
+                      '%s: %s' % (group[2], status_bytes[newbyte][2])]])
+        self.ss_block, self.es_block = old_ss_block, old_es_block
+        # Deliberately not resetting self.cmd or self.state.
+
+    def handle_garbage_msg(self, newbyte):
+        # Handle messages that are either not handled or are corrupt.
+        self.es_block = self.es
+        if newbyte is not None:
+            self.cmd.append(newbyte)
+            return
+        payload = '<empty>'
+        max_bytes = 16 # Put a limit on the length on the hex dump.
+        for index in range(len(self.cmd)):
+            if index == max_bytes:
+                payload += ' ...'
+                break
+            if index == 0:
+                payload = '0x%02x' % self.cmd[index]
+            else:
+                payload += ' 0x%02x' % self.cmd[index]
+        self.putx([2, ['UNHANDLED DATA: %s' % payload,
+                      'UNHANDLED', '???', '?']])
         self.cmd, self.state = [], 'IDLE'
+        self.hard_clear_status_byte()
+
+    def handle_state(self, state, newbyte):
+        # 'newbyte' can either be:
+        # 1. Value between 0x00-0xff, deal with the byte normally.
+        # 2. Value of 'None' which means "flush any buffered data".
+        if state == 'HANDLE CHANNEL MSG':
+            self.handle_channel_msg(newbyte)
+        elif state == 'HANDLE SYSEX MSG':
+            self.handle_sysex_msg(newbyte)
+        elif state == 'HANDLE SYSCOMMON MSG':
+            self.handle_syscommon_msg(newbyte)
+        elif state == 'HANDLE SYSREALTIME MSG':
+            self.handle_sysrealtime_msg(newbyte)
+        elif state == 'BUFFER GARBAGE MSG':
+            self.handle_garbage_msg(newbyte)
+
+    def get_next_state(self, newbyte):
+        # 'newbyte' must be a valid byte between 0x00 and 0xff.
+        #
+        # Try to determine the state based off of the 'newbyte' parameter.
+        if newbyte in range(0x80, 0xef + 1):
+            return 'HANDLE CHANNEL MSG'
+        if newbyte == 0xf0:
+            return 'HANDLE SYSEX MSG'
+        if newbyte in range(0xf1, 0xf7):
+            return'HANDLE SYSCOMMON MSG'
+        if newbyte in range(0xf8, 0xff + 1):
+            return 'HANDLE SYSREALTIME MSG'
+        # Passing 0xf7 is an error; messages don't start with 0xf7.
+        if newbyte == 0xf7:
+            return 'BUFFER GARBAGE MSG'
+        # Next, base the state off of self.status_byte.
+        if self.status_byte < 0x80:
+            return 'BUFFER GARBAGE MSG'
+        return self.get_next_state(self.status_byte)
 
     def decode(self, ss, es, data):
         ptype, rxtx, pdata = data
+        state = 'IDLE'
 
         # For now, ignore all UART packets except the actual data packets.
         if ptype != 'DATA':
             return
 
-        self.ss, self.es = ss, es
+        # We're only interested in the byte value (not individual bits).
+        pdata = pdata[0]
 
         # Short MIDI overview:
         #  - Status bytes are 0x80-0xff, data bytes are 0x00-0x7f.
         #  - Most messages: 1 status byte, 1-2 data bytes.
         #  - Real-time system messages: always 1 byte.
         #  - SysEx messages: 1 status byte, n data bytes, EOX byte.
+        #
+        # Aspects of the MIDI protocol that complicate decoding:
+        #  - MIDI System Realtime messages can briefly interrupt other
+        #    messages already in progress.
+        #  - "Running Status" allows for omitting the status byte in most
+        #    scenarios if sequential messages have the same status byte.
+        #  - System Exclusive (SysEx) messages can be terminated by ANY
+        #    status byte (not limited to EOX byte).
 
         # State machine.
-        if self.state == 'IDLE':
-            # Wait until we see a status byte (bit 7 must be set).
-            if pdata < 0x80:
-                return # TODO: How to handle? Ignore?
+        if pdata >= 0x80 and pdata != 0xf7:
+            state = self.get_next_state(pdata)
+            if state != 'HANDLE SYSREALTIME MSG' and self.state != 'IDLE':
+                # Flush the previous data since a new message is starting.
+                self.handle_state(self.state, None)
+            # Cache ss and es -after- flushing previous data.
+            self.ss, self.es = ss, es
             # This is a status byte, remember the start sample.
-            self.ss_block = ss
-            if pdata in range(0x80, 0xef + 1):
-                self.state = 'HANDLE CHANNEL MSG'
-            elif pdata == 0xf0:
-                self.state = 'HANDLE SYSEX MSG'
-            elif pdata in range(0xf1, 0xf7 + 1):
-                self.state = 'HANDLE SYSCOMMON MSG'
-            elif pdata in range(0xf8, 0xff + 1):
-                self.state = 'HANDLE SYSREALTIME MSG'
-
-        # Yes, this is intentionally _not_ an 'elif' here.
-        if self.state == 'HANDLE CHANNEL MSG':
-            self.handle_channel_msg(pdata)
-        elif self.state == 'HANDLE SYSEX MSG':
-            self.handle_sysex_msg(pdata)
-        elif self.state == 'HANDLE SYSCOMMON MSG':
-            self.handle_syscommon_msg(pdata)
-        elif self.state == 'HANDLE SYSREALTIME MSG':
-            self.handle_sysrealtime_msg(pdata)
+            if state != 'HANDLE SYSREALTIME MSG':
+                self.ss_block = ss
+        elif self.state == 'IDLE' or self.state == 'BUFFER GARBAGE MSG':
+            # Deal with "running status" or that we're buffering garbage.
+            self.ss, self.es = ss, es
+            if self.state == 'IDLE':
+                self.ss_block = ss
+            state = self.get_next_state(pdata)
         else:
-            raise Exception('Invalid state: %s' % self.state)
+            self.ss, self.es = ss, es
+            state = self.state
 
+        # Yes, this is intentionally _not_ an 'elif' here.
+        if state != 'HANDLE SYSREALTIME MSG':
+            self.state = state
+        if state == 'BUFFER GARBAGE MSG':
+            self.status_byte = 0
+        self.handle_state(state, pdata)
diff --git a/decoders/mlx90614/__init__.py b/decoders/mlx90614/__init__.py
index 29cb2a9..e985c91 100644
--- a/decoders/mlx90614/__init__.py
+++ b/decoders/mlx90614/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'i2c' PD and decodes the Melexis MLX90614
 infrared thermometer protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/mlx90614/pd.py b/decoders/mlx90614/pd.py
index edc770d..0a3abba 100644
--- a/decoders/mlx90614/pd.py
+++ b/decoders/mlx90614/pd.py
@@ -34,7 +34,7 @@ class Decoder(srd.Decoder):
         ('kelvin', 'Temperature in Kelvin'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IGNORE START REPEAT'
         self.data = []
 
@@ -73,6 +73,3 @@ class Decoder(srd.Decoder):
                 self.putx([1, ['Temperature: %3.2f K' % kelvin]])
                 self.state = 'IGNORE START REPEAT'
                 self.data = []
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/dcf77/__init__.py b/decoders/modbus/__init__.py
similarity index 70%
copy from decoders/dcf77/__init__.py
copy to decoders/modbus/__init__.py
index 04805c2..e9f0deb 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/modbus/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Bart de Waal <bart at waalamo.com>
 ##
 ## 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
@@ -19,12 +19,11 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This decoder stacks on top of the 'uart' PD and decodes Modbus RTU,
+a protocol with a single a client and one or more servers.
 
-Details:
-http://en.wikipedia.org/wiki/DCF77
+The RX channel will be checked for both client->server and server->client
+communication, the TX channel only for client->server.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/modbus/pd.py b/decoders/modbus/pd.py
new file mode 100644
index 0000000..3420f99
--- /dev/null
+++ b/decoders/modbus/pd.py
@@ -0,0 +1,931 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Bart de Waal <bart at waalamo.com>
+##
+## 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 3 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, see <http://www.gnu.org/licenses/>.
+##
+
+import sigrokdecode as srd
+from math import ceil
+
+RX = 0
+TX = 1
+
+class No_more_data(Exception):
+    '''This exception is a signal that we should stop parsing an ADU as there
+    is no more data to parse.'''
+    pass
+
+class Data:
+    '''The Data class is used to hold the bytes from the serial decode.'''
+    def __init__(self, start, end, data):
+        self.start = start
+        self.end = end
+        self.data = data
+
+class Modbus_ADU:
+    '''An Application Data Unit is what Modbus calls one message.
+    Protocol decoders are supposed to keep track of state and then provide
+    decoded data to the backend as it reads it. In Modbus' case, the state is
+    the ADU up to that point. This class represents the state and writes the
+    messages to the backend.
+    This class is for the common infrastructure between CS and SC. It should
+    not be used directly, only inhereted from.'''
+
+    def __init__(self, parent, start, write_channel, annotation_prefix):
+        self.data = [] # List of all the data received up to now
+        self.parent = parent # Reference to the decoder object
+        self.start = start
+        self.last_read = start # The last moment parsed by this ADU object
+        self.write_channel = write_channel
+        self.last_byte_put = -1
+        self.annotation_prefix = annotation_prefix
+        # Any Modbus message needs to be at least 4 bytes long. The Modbus
+        # function may make this longer.
+        self.minimum_length = 4
+
+        # This variable is used by an external function to determine when the
+        # next frame should be started.
+        self.startNewFrame = False
+
+        # If there is an error in a frame, we'd like to highlight it. Keep
+        # track of errors.
+        self.hasError = False
+
+    def add_data(self, start, end, data):
+        '''Let the frame handle another piece of data.
+        start: start of this data
+        end: end of this data
+        data: data as received from the UART decoder'''
+        ptype, rxtx, pdata = data
+        self.last_read = end
+        if ptype == 'DATA':
+            self.data.append(Data(start, end, pdata[0]))
+            self.parse() # parse() is defined in the specific type of ADU.
+
+    def puti(self, byte_to_put, annotation, message):
+        '''This class keeps track of how much of the data has already been
+        annotated. This function tells the parent class to write message, but
+        only if it hasn't written about this bit before.
+        byte_to_put: Only write if it hasn't yet written byte_to_put. It will
+                     write from the start of self.last_byte_put+1 to the end
+                     of byte_to_put.
+        annotation: Annotation to write to, without annotation_prefix.
+        message: Message to write.'''
+        if byte_to_put > len(self.data) - 1:
+            # If the byte_to_put hasn't been read yet.
+            raise No_more_data
+
+        if annotation == 'error':
+            self.hasError = True
+
+        if byte_to_put > self.last_byte_put:
+            self.parent.puta(
+                self.data[self.last_byte_put + 1].start,
+                self.data[byte_to_put].end,
+                self.annotation_prefix + annotation,
+                message)
+            self.last_byte_put = byte_to_put
+            raise No_more_data
+
+    def putl(self, annotation, message, maximum=None):
+        '''Puts the last byte on the stack with message. The contents of the
+        last byte will be applied to message using format.'''
+        last_byte_address = len(self.data) - 1
+        if maximum is not None and last_byte_address > maximum:
+            return
+        self.puti(last_byte_address, annotation,
+                  message.format(self.data[-1].data))
+
+    def close(self, message_overflow):
+        '''Function to be called when next message is started. As there is
+        always space between one message and the next, we can use that space
+        for errors at the end.'''
+        # TODO: Figure out how to make this happen for last message.
+        data = self.data
+        if len(data) < self.minimum_length:
+            if len(data) == 0:
+                # Sometimes happens with noise, safe to ignore.
+                return
+            self.parent.puta(
+                data[self.last_byte_put].end, message_overflow,
+                self.annotation_prefix + 'error',
+                'Message too short or not finished')
+            self.hasError = True
+        if self.hasError and self.parent.options['channel'] == 'RX':
+            # If we are on RX mode (so client->server and server->client
+            # messages can be seperated) we like to mark blocks containing
+            # errors. We don't do this in TX mode, because then we interpret
+            # each frame as both a client->server and server->client frame, and
+            # one of those is bound to contain an error, making highlighting
+            # frames useless.
+            self.parent.puta(data[0].start, data[-1].end,
+                             'error-indication', 'Frame contains error')
+        if len(data) > 256:
+            try:
+                self.puti(len(data) - 1, self.annotation_prefix + 'error',
+                    'Modbus data frames are limited to 256 bytes')
+            except No_more_data:
+                pass
+
+    def check_crc(self, byte_to_put):
+        '''Check the CRC code, data[byte_to_put] is the 2nd byte of the CRC.'''
+        crc_byte1, crc_byte2 = self.calc_crc(byte_to_put)
+        data = self.data
+        if data[-2].data == crc_byte1 and data[-1].data == crc_byte2:
+            self.puti(byte_to_put, 'crc', 'CRC correct')
+        else:
+            self.puti(byte_to_put, 'error',
+                'CRC should be {} {}'.format(crc_byte1, crc_byte2))
+
+    def half_word(self, start):
+        '''Return the half word (16 bit) value starting at start bytes in. If
+        it goes out of range it raises the usual errors.'''
+        if (start + 1) > (len(self.data) - 1):
+            # If there isn't enough length to access data[start + 1].
+            raise No_more_data
+        return self.data[start].data * 0x100 + self.data[start + 1].data
+
+    def calc_crc(self, last_byte):
+        '''Calculate the CRC, as described in the spec.
+        The last byte of the CRC should be data[last_byte].'''
+        if last_byte < 3:
+            # Every Modbus ADU should be as least 4 long, so we should never
+            # have to calculate a CRC on something shorter.
+            raise Exception('Could not calculate CRC: message too short')
+
+        result = 0xFFFF
+        magic_number = 0xA001 # As defined in the modbus specification.
+        for byte in self.data[:last_byte - 1]:
+            result = result ^ byte.data
+            for i in range(8):
+                LSB = result & 1
+                result = result >> 1
+                if (LSB): # If the LSB is true.
+                    result = result ^ magic_number
+        byte1 = result & 0xFF
+        byte2 = (result & 0xFF00) >> 8
+        return (byte1, byte2)
+
+    def parse_write_single_coil(self):
+        '''Parse function 5, write single coil.'''
+        self.minimum_length = 8
+
+        self.puti(1, 'function', 'Function 5: Write Single Coil')
+
+        address = self.half_word(2)
+        self.puti(3, 'address',
+            'Address 0x{:X} / {:d}'.format(address, address + 10000))
+
+        raw_value = self.half_word(4)
+        value = 'Invalid Coil Value'
+        if raw_value == 0x0000:
+            value = 'Coil Value OFF'
+        elif raw_value == 0xFF00:
+            value = 'Coil Value ON'
+        self.puti(5, 'data', value)
+
+        self.check_crc(7)
+
+    def parse_write_single_register(self):
+        '''Parse function 6, write single register.'''
+        self.minimum_length = 8
+
+        self.puti(1, 'function', 'Function 6: Write Single Register')
+
+        address = self.half_word(2)
+        self.puti(3, 'address',
+            'Address 0x{:X} / {:d}'.format(address, address + 30000))
+
+        value = self.half_word(4)
+        value_formatted = 'Register Value 0x{0:X} / {0:d}'.format(value)
+        self.puti(5, 'data', value_formatted)
+
+        self.check_crc(7)
+
+    def parse_diagnostics(self):
+        '''Parse function 8, diagnostics. This function has many subfunctions,
+        but they are all more or less the same.'''
+        self.minimum_length = 8
+
+        self.puti(1, 'function', 'Function 8: Diagnostics')
+
+        diag_subfunction = {
+            0: 'Return Query data',
+            1: 'Restart Communications Option',
+            2: 'Return Diagnostics Register',
+            3: 'Change ASCII Input Delimiter',
+            4: 'Force Listen Only Mode',
+            10: 'Clear Counters and Diagnostic Register',
+            11: 'Return Bus Message Count',
+            12: 'Return Bus Communication Error Count',
+            13: 'Return Bus Exception Error Count',
+            14: 'Return Slave Message Count',
+            15: 'Return Slave No Response Count',
+            16: 'Return Slave NAK Count',
+            17: 'Return Slave Busy Count',
+            18: 'Return Bus Character Overrun Count',
+            20: 'Return Overrun Counter and Flag',
+        }
+        subfunction = self.half_word(2)
+        subfunction_name = diag_subfunction.get(subfunction,
+                                                'Reserved subfunction')
+        self.puti(3, 'data',
+            'Subfunction {}: {}'.format(subfunction, subfunction_name))
+
+        diagnostic_data = self.half_word(4)
+        self.puti(5, 'data',
+            'Data Field: {0} / 0x{0:04X}'.format(diagnostic_data))
+
+        self.check_crc(7)
+
+    def parse_mask_write_register(self):
+        '''Parse function 22, Mask Write Register.'''
+        self.minimum_length = 10
+        data = self.data
+
+        self.puti(1, 'function', 'Function 22: Mask Write Register')
+
+        address = self.half_word(2)
+        self.puti(3, 'address',
+            'Address 0x{:X} / {:d}'.format(address, address + 30001))
+
+        self.half_word(4) # To make sure we don't oveflow data.
+        and_mask_1 = data[4].data
+        and_mask_2 = data[5].data
+        self.puti(5, 'data',
+            'AND mask: {:08b} {:08b}'.format(and_mask_1, and_mask_2))
+
+        self.half_word(6) # To make sure we don't oveflow data.
+        or_mask_1 = data[6].data
+        or_mask_2 = data[7].data
+        self.puti(7, 'data',
+            'OR mask: {:08b} {:08b}'.format(or_mask_1, or_mask_2))
+
+        self.check_crc(9)
+
+    def parse_not_implemented(self):
+        '''Explicitly mark certain functions as legal functions, but not
+        implemented in this parser. This is due to the author not being able to
+        find anything (hardware or software) that supports these functions.'''
+        # TODO: Implement these functions.
+
+        # Mentioning what function it is is no problem.
+        function = self.data[1].data
+        functionname = {
+            20: 'Read File Record',
+            21: 'Write File Record',
+            24: 'Read FIFO Queue',
+            43: 'Read Device Identification/Encapsulated Interface Transport',
+        }[function]
+        self.puti(1, 'function',
+            'Function {}: {} (not supported)'.format(function, functionname))
+
+        # From there on out we can keep marking it unsupported.
+        self.putl('data', 'This function is not currently supported')
+
+class Modbus_ADU_SC(Modbus_ADU):
+    '''SC stands for Server -> Client.'''
+    def parse(self):
+        '''Select which specific Modbus function we should parse.'''
+        data = self.data
+
+        # This try-catch is being used as flow control.
+        try:
+            server_id = data[0].data
+            if 1 <= server_id <= 247:
+                message = 'Slave ID: {}'.format(server_id)
+            else:
+                message = 'Slave ID {} is invalid'
+            self.puti(0, 'server-id', message)
+
+            function = data[1].data
+            if function == 1 or function == 2:
+                self.parse_read_bits()
+            elif function == 3 or function == 4 or function == 23:
+                self.parse_read_registers()
+            elif function == 5:
+                self.parse_write_single_coil()
+            elif function == 6:
+                self.parse_write_single_register()
+            elif function == 7:
+                self.parse_read_exception_status()
+            elif function == 8:
+                self.parse_diagnostics()
+            elif function == 11:
+                self.parse_get_comm_event_counter()
+            elif function == 12:
+                self.parse_get_comm_event_log()
+            elif function == 15 or function == 16:
+                self.parse_write_multiple()
+            elif function == 17:
+                self.parse_report_server_id()
+            elif function == 22:
+                self.parse_mask_write_register()
+            elif function in {21, 21, 24, 43}:
+                self.parse_not_implemented()
+            elif function > 0x80:
+                self.parse_error()
+            else:
+                self.puti(1, 'error',
+                          'Unknown function: {}'.format(data[1].data))
+                self.putl('error', 'Unknown function')
+
+            # If the message gets here without raising an exception, the
+            # message goes on longer than it should.
+            self.putl('error', 'Message too long')
+
+        except No_more_data:
+            # Just a message saying we don't need to parse anymore this round.
+            pass
+
+    def parse_read_bits(self):
+        self.mimumum_length = 5
+
+        data = self.data
+        function = data[1].data
+
+        if function == 1:
+            self.puti(1, 'function', 'Function 1: Read Coils')
+        else:
+            self.puti(1, 'function', 'Function 2: Read Discrete Inputs')
+
+        bytecount = self.data[2].data
+        self.minimum_length = 5 + bytecount # 3 before data, 2 CRC.
+        self.puti(2, 'length', 'Byte count: {}'.format(bytecount))
+
+        # From here on out, we expect registers on 3 and 4, 5 and 6 etc.
+        # So registers never start when the length is even.
+        self.putl('data', '{:08b}', bytecount + 2)
+        self.check_crc(bytecount + 4)
+
+    def parse_read_registers(self):
+        self.mimumum_length = 5
+
+        data = self.data
+
+        function = data[1].data
+        if function == 3:
+            self.puti(1, 'function', 'Function 3: Read Holding Registers')
+        elif function == 4:
+            self.puti(1, 'function', 'Function 4: Read Input Registers')
+        elif function == 23:
+            self.puti(1, 'function', 'Function 23: Read/Write Multiple Registers')
+
+        bytecount = self.data[2].data
+        self.minimum_length = 5 + bytecount # 3 before data, 2 CRC.
+        if bytecount % 2 == 0:
+            self.puti(2, 'length', 'Byte count: {}'.format(bytecount))
+        else:
+            self.puti(2, 'error',
+                'Error: Odd byte count ({})'.format(bytecount))
+
+        # From here on out, we expect registers on 3 and 4, 5 and 6 etc.
+        # So registers never start when the length is even.
+        if len(data) % 2 == 1:
+            register_value = self.half_word(-2)
+            self.putl('data', '0x{0:04X} / {0}'.format(register_value),
+                      bytecount + 2)
+        else:
+            raise No_more_data
+
+        self.check_crc(bytecount + 4)
+
+    def parse_read_exception_status(self):
+        self.mimumum_length = 5
+
+        self.puti(1, 'function', 'Function 7: Read Exception Status')
+        exception_status = self.data[2].data
+        self.puti(2, 'data',
+                  'Exception status: {:08b}'.format(exception_status))
+        self.check_crc(4)
+
+    def parse_get_comm_event_counter(self):
+        self.mimumum_length = 8
+
+        self.puti(1, 'function', 'Function 11: Get Comm Event Counter')
+
+        status = self.half_word(2)
+        if status == 0x0000:
+            self.puti(3, 'data', 'Status: not busy')
+        elif status == 0xFFFF:
+            self.puti(3, 'data', 'Status: busy')
+        else:
+            self.puti(3, 'error', 'Bad status: 0x{:04X}'.format(status))
+
+        count = self.half_word(4)
+        self.puti(5, 'data', 'Event Count: {}'.format(count))
+        self.check_crc(7)
+
+    def parse_get_comm_event_log(self):
+        self.mimumum_length = 11
+        self.puti(1, 'function', 'Function 12: Get Comm Event Log')
+
+        data = self.data
+
+        bytecount = data[2].data
+        self.puti(2, 'length', 'Bytecount: {}'.format(bytecount))
+        # The bytecount is the length of everything except the slaveID,
+        # function code, bytecount and CRC.
+        self.mimumum_length = 5 + bytecount
+
+        status = self.half_word(3)
+        if status == 0x0000:
+            self.puti(4, 'data', 'Status: not busy')
+        elif status == 0xFFFF:
+            self.puti(4, 'data', 'Status: busy')
+        else:
+            self.puti(4, 'error', 'Bad status: 0x{:04X}'.format(status))
+
+        event_count = self.half_word(5)
+        self.puti(6, 'data', 'Event Count: {}'.format(event_count))
+
+        message_count = self.half_word(7)
+        self.puti(8, 'data', 'Message Count: {}'.format(message_count))
+
+        self.putl('data', 'Event: 0x{:02X}'.format(data[-1].data),
+                  bytecount + 2)
+
+        self.check_crc(bytecount + 4)
+
+    def parse_write_multiple(self):
+        '''Function 15 and 16 are almost the same, so we can parse them both
+        using one function.'''
+        self.mimumum_length = 8
+
+        function = self.data[1].data
+        if function == 15:
+            data_unit = 'Coils'
+            max_outputs = 0x07B0
+            long_address_offset = 10001
+        elif function == 16:
+            data_unit = 'Registers'
+            max_outputs = 0x007B
+            long_address_offset = 30001
+
+        self.puti(1, 'function',
+            'Function {}: Write Multiple {}'.format(function, data_unit))
+
+        starting_address = self.half_word(2)
+        # Some instruction manuals use a long form name for addresses, this is
+        # listed here for convienience.
+        address_name = long_address_offset + starting_address
+        self.puti(3, 'address',
+            'Start at address 0x{:X} / {:d}'.format(starting_address,
+                                                    address_name))
+
+        quantity_of_outputs = self.half_word(4)
+        if quantity_of_outputs <= max_outputs:
+            self.puti(5, 'data',
+                'Write {} {}'.format(quantity_of_outputs, data_unit))
+        else:
+            self.puti(5, 'error',
+                'Bad value: {} {}. Max is {}'.format(quantity_of_outputs,
+                                                     data_unit, max_outputs))
+
+        self.check_crc(7)
+
+    def parse_report_server_id(self):
+        # Buildup of this function:
+        # 1 byte serverID
+        # 1 byte function (17)
+        # 1 byte bytecount
+        # 1 byte serverID (counts for bytecount)
+        # 1 byte Run Indicator Status (counts for bytecount)
+        # bytecount - 2 bytes of device specific data (counts for bytecount)
+        # 2 bytes of CRC
+        self.mimumum_length = 7
+        data = self.data
+        self.puti(1, 'function', 'Function 17: Report Server ID')
+
+        bytecount = data[2].data
+        self.puti(2, 'length', 'Data is {} bytes long'.format(bytecount))
+
+        self.puti(3, 'data', 'serverID: {}'.format(data[3].data))
+
+        run_indicator_status = data[4].data
+        if run_indicator_status == 0x00:
+            self.puti(4, 'data', 'Run Indicator status: Off')
+        elif run_indicator_status == 0xFF:
+            self.puti(4, 'data', 'Run Indicator status: On')
+        else:
+            self.puti(4, 'error',
+                'Bad Run Indicator status: 0x{:X}'.format(run_indicator_status))
+
+        self.putl('data', 'Device specific data: {}, "{}"'.format(data[-1].data,
+                  chr(data[-1].data)), 2 + bytecount)
+
+        self.check_crc(4 + bytecount)
+
+    def parse_error(self):
+        '''Parse a Modbus error message.'''
+        self.mimumum_length = 5
+        # The function code of an error is always 0x80 above the function call
+        # that caused it.
+        functioncode = self.data[1].data - 0x80
+
+        functions = {
+            1: 'Read Coils',
+            2: 'Read Discrete Inputs',
+            3: 'Read Holding Registers',
+            4: 'Read Input Registers',
+            5: 'Write Single Coil',
+            6: 'Write Single Register',
+            7: 'Read Exception Status',
+            8: 'Diagnostic',
+            11: 'Get Com Event Counter',
+            12: 'Get Com Event Log',
+            15: 'Write Multiple Coils',
+            16: 'Write Multiple Registers',
+            17: 'Report Slave ID',
+            20: 'Read File Record',
+            21: 'Write File Record',
+            22: 'Mask Write Register',
+            23: 'Read/Write Multiple Registers',
+            24: 'Read FIFO Queue',
+            43: 'Read Device Identification/Encapsulated Interface Transport',
+        }
+        functionname = '{}: {}'.format(functioncode,
+            functions.get(functioncode, 'Unknown function'))
+        self.puti(1, 'function',
+                  'Error for function {}'.format(functionname))
+
+        error = self.data[2].data
+        errorcodes = {
+            1: 'Illegal Function',
+            2: 'Illegal Data Address',
+            3: 'Illegal Data Value',
+            4: 'Slave Device Failure',
+            5: 'Acknowledge',
+            6: 'Slave Device Busy',
+            8: 'Memory Parity Error',
+            10: 'Gateway Path Unavailable',
+            11: 'Gateway Target Device failed to respond',
+        }
+        errorname = '{}: {}'.format(error, errorcodes.get(error, 'Unknown'))
+        self.puti(2, 'data', 'Error {}'.format(errorname))
+        self.check_crc(4)
+
+class Modbus_ADU_CS(Modbus_ADU):
+    '''CS stands for Client -> Server.'''
+    def parse(self):
+        '''Select which specific Modbus function we should parse.'''
+        data = self.data
+
+        # This try-catch is being used as flow control.
+        try:
+            server_id = data[0].data
+            message = ''
+            if server_id == 0:
+                message = 'Broadcast message'
+            elif 1 <= server_id <= 247:
+                message = 'Slave ID: {}'.format(server_id)
+            elif 248 <= server_id <= 255:
+                message = 'Slave ID: {} (reserved address)'.format(server_id)
+            self.puti(0, 'server-id', message)
+
+            function = data[1].data
+            if function >= 1 and function <= 4:
+                self.parse_read_data_command()
+            if function == 5:
+                self.parse_write_single_coil()
+            if function == 6:
+                self.parse_write_single_register()
+            if function in {7, 11, 12, 17}:
+                self.parse_single_byte_request()
+            elif function == 8:
+                self.parse_diagnostics()
+            if function in {15, 16}:
+                self.parse_write_multiple()
+            elif function == 22:
+                self.parse_mask_write_register()
+            elif function == 23:
+                self.parse_read_write_registers()
+            elif function in {21, 21, 24, 43}:
+                self.parse_not_implemented()
+            else:
+                self.puti(1, 'error',
+                          'Unknown function: {}'.format(data[1].data))
+                self.putl('error', 'Unknown function')
+
+            # If the message gets here without raising an exception, the
+            # message goes on longer than it should.
+            self.putl('error', 'Message too long')
+
+        except No_more_data:
+            # Just a message saying we don't need to parse anymore this round.
+            pass
+
+    def parse_read_data_command(self):
+        '''Interpret a command to read x units of data starting at address, ie
+        functions 1, 2, 3 and 4, and write the result to the annotations.'''
+        data = self.data
+        self.minimum_length = 8
+
+        function = data[1].data
+        functionname = {1: 'Read Coils',
+                        2: 'Read Discrete Inputs',
+                        3: 'Read Holding Registers',
+                        4: 'Read Input Registers',
+                        }[function]
+
+        self.puti(1, 'function',
+                  'Function {}: {}'.format(function, functionname))
+
+        starting_address = self.half_word(2)
+        # Some instruction manuals use a long form name for addresses, this is
+        # listed here for convienience.
+        # Example: holding register 60 becomes 30061.
+        address_name = 10000 * function + 1 + starting_address
+        self.puti(3, 'address',
+            'Start at address 0x{:X} / {:d}'.format(starting_address,
+                                                    address_name))
+
+        self.puti(5, 'length',
+                  'Read {:d} units of data'.format(self.half_word(4)))
+        self.check_crc(7)
+
+    def parse_single_byte_request(self):
+        '''Some Modbus functions have no arguments, this parses those.'''
+        function = self.data[1].data
+        function_name = {7: 'Read Exception Status',
+                         11: 'Get Comm Event Counter',
+                         12: 'Get Comm Event Log',
+                         17: 'Report Slave ID',
+                         }[function]
+        self.puti(1, 'function',
+                  'Function {}: {}'.format(function, function_name))
+
+        self.check_crc(3)
+
+    def parse_write_multiple(self):
+        '''Function 15 and 16 are almost the same, so we can parse them both
+        using one function.'''
+        self.mimumum_length = 9
+
+        function = self.data[1].data
+        if function == 15:
+            data_unit = 'Coils'
+            max_outputs = 0x07B0
+            ratio_bytes_data = 1/8
+            long_address_offset = 10001
+        elif function == 16:
+            data_unit = 'Registers'
+            max_outputs = 0x007B
+            ratio_bytes_data = 2
+            long_address_offset = 30001
+
+        self.puti(1, 'function',
+            'Function {}: Write Multiple {}'.format(function, data_unit))
+
+        starting_address = self.half_word(2)
+        # Some instruction manuals use a long form name for addresses, this is
+        # listed here for convienience.
+        address_name = long_address_offset + starting_address
+        self.puti(3, 'address',
+            'Start at address 0x{:X} / {:d}'.format(starting_address,
+                                                    address_name))
+
+        quantity_of_outputs = self.half_word(4)
+        if quantity_of_outputs <= max_outputs:
+            self.puti(5, 'length',
+                'Write {} {}'.format(quantity_of_outputs, data_unit))
+        else:
+            self.puti(5, 'error',
+                'Bad value: {} {}. Max is {}'.format(quantity_of_outputs,
+                                                     data_unit, max_outputs))
+        proper_bytecount = ceil(quantity_of_outputs * ratio_bytes_data)
+
+        bytecount = self.data[6].data
+        if bytecount == proper_bytecount:
+            self.puti(6, 'length', 'Byte count: {}'.format(bytecount))
+        else:
+            self.puti(6, 'error',
+                'Bad byte count, is {}, should be {}'.format(bytecount,
+                                                             proper_bytecount))
+        self.mimumum_length = bytecount + 9
+
+        self.putl('data', 'Value 0x{:X}', 6 + bytecount)
+
+        self.check_crc(bytecount + 8)
+
+    def parse_read_file_record(self):
+        self.puti(1, 'function', 'Function 20: Read file records')
+
+        data = self.data
+
+        bytecount = data[2].data
+
+        self.minimum_length = 5 + bytecount
+        # 1 for serverID, 1 for function, 1 for bytecount, 2 for CRC.
+
+        if 0x07 <= bytecount <= 0xF5:
+            self.puti(2, 'length', 'Request is {} bytes long'.format(bytecount))
+        else:
+            self.puti(2, 'error',
+                'Request claims to be {} bytes long, legal values are between'
+                ' 7 and 247'.format(bytecount))
+
+        current_byte = len(data) - 1
+        # Function 20 is a number of sub-requests, the first starting at 3,
+        # the total length of the sub-requests is bytecount.
+        if current_byte <= bytecount + 2:
+            step = (current_byte - 3) % 7
+            if step == 0:
+                if data[current_byte].data == 6:
+                    self.puti(current_byte, 'data', 'Start sub-request')
+                else:
+                    self.puti(current_byte, 'error',
+                        'First byte of subrequest should be 0x06')
+            elif step == 1:
+                raise No_more_data
+            elif step == 2:
+                file_number = self.half_word(current_byte - 1)
+                self.puti(current_byte, 'data',
+                          'Read File number {}'.format(file_number))
+            elif step == 3:
+                raise No_more_data
+            elif step == 4:
+                record_number = self.half_word(current_byte - 1)
+                self.puti(current_byte, 'address',
+                    'Read from record number {}'.format(record_number))
+                # TODO: Check if within range.
+            elif step == 5:
+                raise No_more_data
+            elif step == 6:
+                records_to_read = self.half_word(current_byte - 1)
+                self.puti(current_byte, 'length',
+                    'Read {} records'.format(records_to_read))
+        self.check_crc(4 + bytecount)
+
+    def parse_read_write_registers(self):
+        '''Parse function 23: Read/Write multiple registers.'''
+        self.minimum_length = 13
+
+        self.puti(1, 'function', 'Function 23: Read/Write Multiple Registers')
+
+        starting_address = self.half_word(2)
+        # Some instruction manuals use a long form name for addresses, this is
+        # listed here for convienience.
+        # Example: holding register 60 becomes 30061.
+        address_name = 30001 + starting_address
+        self.puti(3, 'address',
+            'Read starting at address 0x{:X} / {:d}'.format(starting_address,
+                                                            address_name))
+
+        self.puti(5, 'length', 'Read {:d} units of data'.format(self.half_word(4)))
+
+        starting_address = self.half_word(6)
+        self.puti(7, 'address',
+            'Write starting at address 0x{:X} / {:d}'.format(starting_address,
+                                                             address_name))
+
+        quantity_of_outputs = self.half_word(8)
+        self.puti(9, 'length',
+                           'Write {} registers'.format(quantity_of_outputs))
+        proper_bytecount = quantity_of_outputs * 2
+
+        bytecount = self.data[10].data
+        if bytecount == proper_bytecount:
+            self.puti(10, 'length', 'Byte count: {}'.format(bytecount))
+        else:
+            self.puti(10, 'error',
+                'Bad byte count, is {}, should be {}'.format(bytecount,
+                                                             proper_bytecount))
+        self.mimumum_length = bytecount + 13
+
+        self.putl('data', 'Data, value 0x{:02X}', 10 + bytecount)
+
+        self.check_crc(bytecount + 12)
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'modbus'
+    name = 'Modbus'
+    longname = 'Modbus RTU over RS232/RS485'
+    desc = 'Modbus RTU protocol for industrial applications.'
+    license = 'gplv3+'
+    inputs = ['uart']
+    outputs = ['modbus']
+    annotations = (
+        ('sc-server-id', ''),
+        ('sc-function', ''),
+        ('sc-crc', ''),
+        ('sc-address', ''),
+        ('sc-data', ''),
+        ('sc-length', ''),
+        ('sc-error', ''),
+        ('cs-server-id', ''),
+        ('cs-function', ''),
+        ('cs-crc', ''),
+        ('cs-address', ''),
+        ('cs-data', ''),
+        ('cs-length', ''),
+        ('cs-error', ''),
+        ('error-indication', ''),
+    )
+    annotation_rows = (
+        ('sc', 'Server->client', (0, 1, 2, 3, 4, 5, 6)),
+        ('cs', 'Client->server', (7, 8, 9, 10, 11, 12, 13)),
+        ('error-indicator', 'Errors in frame', (14,)),
+    )
+    options = (
+        {'id': 'channel', 'desc': 'Server -> client channel', 'default': 'RX',
+            'values': ('RX', 'TX')},
+    )
+
+    def __init__(self):
+        self.ADUSc = None # Start off with empty slave -> client ADU.
+        self.ADUCs = None # Start off with empty client -> slave ADU.
+
+        # The reason we have both (despite not supporting full duplex comms) is
+        # because we want to be able to decode the message as both client ->
+        # server and server -> client, and let the user see which of the two
+        # the ADU was.
+
+        self.bitlength = None # We will later test how long a bit is.
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def puta(self, start, end, ann_str, message):
+        '''Put an annotation from start to end, with ann as a
+        string. This means you don't have to know the ann's
+        number to write annotations to it.'''
+        ann = [s[0] for s in self.annotations].index(ann_str)
+        self.put(start, end, self.out_ann, [ann, [message]])
+
+    def decode_adu(self, ss, es, data, direction):
+        '''Decode the next byte or bit (depending on type) in the ADU.
+        ss: Start time of the data
+        es: End time of the data
+        data: Data as passed from the UART decoder
+        direction: Is this data for the Cs (client -> server) or Sc (server ->
+                   client) being decoded right now?'''
+        ptype, rxtx, pdata = data
+
+        # We don't have a nice way to get the baud rate from UART, so we have
+        # to figure out how long a bit lasts. We do this by looking at the
+        # length of (probably) the startbit.
+        if self.bitlength is None:
+            if ptype == 'STARTBIT' or ptype == 'STOPBIT':
+                self.bitlength = es - ss
+            else:
+                # If we don't know the bitlength yet, we can't start decoding.
+                return
+
+        # Select the ADU, create the ADU if needed.
+        # We set ADU.startNewFrame = True when we know the old one is over.
+        if direction == 'Sc':
+            if (self.ADUSc is None) or self.ADUSc.startNewFrame:
+                self.ADUSc = Modbus_ADU_SC(self, ss, TX, 'sc-')
+            ADU = self.ADUSc
+        if direction == 'Cs':
+            if self.ADUCs is None or self.ADUCs.startNewFrame:
+                self.ADUCs = Modbus_ADU_CS(self, ss, TX, 'cs-')
+            ADU = self.ADUCs
+
+        # We need to determine if the last ADU is over.
+        # According to the Modbus spec, there should be 3.5 characters worth of
+        # space between each message. But if within a message there is a length
+        # of more than 1.5 character, that's an error. For our purposes
+        # somewhere between seems fine.
+        # A character is 11 bits long, so (3.5 + 1.5)/2 * 11 ~= 28
+        # TODO: Display error for too short or too long.
+        if (ss - ADU.last_read) <= self.bitlength * 28:
+            ADU.add_data(ss, es, data)
+        else:
+            # It's been too long since the last part of the ADU!
+            # If there is any data in the ADU we need to show it to the user
+            if len(ADU.data) > 0:
+                # Extend errors for 3 bits after last byte, we can guarantee
+                # space.
+                ADU.close(ADU.data[-1].end + self.bitlength * 3)
+
+            ADU.startNewFrame = True
+            # Restart this function, it will make a new ADU for us.
+            self.decode_adu(ss, es, data, direction)
+
+    def decode(self, ss, es, data):
+        ptype, rxtx, pdata = data
+
+        # Decide what ADU(s) we need this packet to go to.
+        # Note that it's possible to go to both ADUs.
+        if rxtx == TX:
+            self.decode_adu(ss, es, data, 'Cs')
+        if rxtx == TX and self.options['channel'] == 'TX':
+            self.decode_adu(ss, es, data, 'Sc')
+        if rxtx == RX and self.options['channel'] == 'RX':
+            self.decode_adu(ss, es, data, 'Sc')
diff --git a/decoders/ir_nec/__init__.py b/decoders/mrf24j40/__init__.py
similarity index 79%
copy from decoders/ir_nec/__init__.py
copy to decoders/mrf24j40/__init__.py
index 84bf428..f0820bd 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/mrf24j40/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Karl Palsson <karlp at tweak.net.au>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'spi' PD and decodes Microchip MRF24J40
+IEEE 802.15.4 2.4 GHz RF tranceiver commands and data.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/mrf24j40/lists.py b/decoders/mrf24j40/lists.py
new file mode 100644
index 0000000..e20b4b9
--- /dev/null
+++ b/decoders/mrf24j40/lists.py
@@ -0,0 +1,166 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Karl Palsson <karlp at tweak.net.au>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+sregs = {
+    0: 'RXMCR',
+    1: 'PANIDL',
+    2: 'PANIDH',
+    3: 'SADRL',
+    4: 'SADRH',
+    5: 'EADR0',
+    6: 'EADR1',
+    7: 'EADR2',
+    8: 'EADR3',
+    9: 'EADR4',
+    0xa: 'EADR5',
+    0xb: 'EADR6',
+    0xc: 'EADR7',
+    0xd: 'RXFLUSH',
+    0xe: 'Reserved',
+    0xf: 'Reserved',
+    0x10: 'ORDER',
+    0x11: 'TXMCR',
+    0x12: 'ACKTMOUT',
+    0x13: 'ESLOTG1',
+    0x14: 'SYMTICKL',
+    0x15: 'SYMTICKH',
+    0x16: 'PACON0',
+    0x17: 'PACON1',
+    0x18: 'PACON2',
+    0x19: 'Reserved',
+    0x1a: 'TXBCON0',
+    0x1b: 'TXNCON',
+    0x1c: 'TXG1CON',
+    0x1d: 'TXG2CON',
+    0x1e: 'ESLOTG23',
+    0x1f: 'ESLOTG45',
+    0x20: 'ESLOTG67',
+    0x21: 'TXPEND',
+    0x22: 'WAKECON',
+    0x23: 'FRMOFFSET',
+    0x24: 'TXSTAT',
+    0x25: 'TXBCON1',
+    0x26: 'GATECLK',
+    0x27: 'TXTIME',
+    0x28: 'HSYMTIMRL',
+    0x29: 'HSYMTIMRH',
+    0x2a: 'SOFTRST',
+    0x2b: 'Reserved',
+    0x2c: 'SECCON0',
+    0x2d: 'SECCON1',
+    0x2e: 'TXSTBL',
+    0x2f: 'Reserved',
+    0x30: 'RXSR',
+    0x31: 'INTSTAT',
+    0x32: 'INTCON',
+    0x33: 'GPIO',
+    0x34: 'TRISGPIO',
+    0x35: 'SLPACK',
+    0x36: 'RFCTL',
+    0x37: 'SECCR2',
+    0x38: 'BBREG0',
+    0x39: 'BBREG1',
+    0x3a: 'BBREG2',
+    0x3b: 'BBREG3',
+    0x3c: 'BBREG4',
+    0x3d: 'Reserved',
+    0x3e: 'BBREG6',
+    0x3f: 'CCAEDTH',
+}
+
+lregs = {
+    0x200: 'RFCON0',
+    0x201: 'RFCON1',
+    0x202: 'RFCON2',
+    0x203: 'RFCON3',
+    0x204: 'Reserved',
+    0x205: 'RFCON5',
+    0x206: 'RFCON6',
+    0x207: 'RFCON7',
+    0x208: 'RFCON8',
+    0x209: 'SLPCAL0',
+    0x20A: 'SLPCAL1',
+    0x20B: 'SLPCAL2',
+    0x20C: 'Reserved',
+    0x20D: 'Reserved',
+    0x20E: 'Reserved',
+    0x20F: 'RFSTATE',
+    0x210: 'RSSI',
+    0x211: 'SLPCON0',
+    0x212: 'Reserved',
+    0x213: 'Reserved',
+    0x214: 'Reserved',
+    0x215: 'Reserved',
+    0x216: 'Reserved',
+    0x217: 'Reserved',
+    0x218: 'Reserved',
+    0x219: 'Reserved',
+    0x21A: 'Reserved',
+    0x21B: 'Reserved',
+    0x21C: 'Reserved',
+    0x21D: 'Reserved',
+    0x21E: 'Reserved',
+    0x21F: 'Reserved',
+    0x220: 'SLPCON1',
+    0x221: 'Reserved',
+    0x222: 'WAKETIMEL',
+    0x223: 'WAKETIMEH',
+    0x224: 'REMCNTL',
+    0x225: 'REMCNTH',
+    0x226: 'MAINCNT0',
+    0x227: 'MAINCNT1',
+    0x228: 'MAINCNT2',
+    0x229: 'MAINCNT3',
+    0x22A: 'Reserved',
+    0x22B: 'Reserved',
+    0x22C: 'Reserved',
+    0x22D: 'Reserved',
+    0x22E: 'Reserved',
+    0x22F: 'TESTMODE',
+    0x230: 'ASSOEADR0',
+    0x231: 'ASSOEADR1',
+    0x232: 'ASSOEADR2',
+    0x233: 'ASSOEADR3',
+    0x234: 'ASSOEADR4',
+    0x235: 'ASSOEADR5',
+    0x236: 'ASSOEADR6',
+    0x237: 'ASSOEADR7',
+    0x238: 'ASSOSADR0',
+    0x239: 'ASSOSADR1',
+    0x23A: 'Reserved',
+    0x23B: 'Reserved',
+    0x23C: 'Unimplemented',
+    0x23D: 'Unimplemented',
+    0x23E: 'Unimplemented',
+    0x23F: 'Unimplemented',
+    0x240: 'UPNONCE0',
+    0x241: 'UPNONCE1',
+    0x242: 'UPNONCE2',
+    0x243: 'UPNONCE3',
+    0x244: 'UPNONCE4',
+    0x245: 'UPNONCE5',
+    0x246: 'UPNONCE6',
+    0x247: 'UPNONCE7',
+    0x248: 'UPNONCE8',
+    0x249: 'UPNONCE9',
+    0x24A: 'UPNONCE10',
+    0x24B: 'UPNONCE11',
+    0x24C: 'UPNONCE12'
+}
diff --git a/decoders/mrf24j40/pd.py b/decoders/mrf24j40/pd.py
new file mode 100644
index 0000000..8ef7017
--- /dev/null
+++ b/decoders/mrf24j40/pd.py
@@ -0,0 +1,134 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Karl Palsson <karlp at tweak.net.au>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from .lists import *
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'mrf24j40'
+    name = 'MRF24J40'
+    longname = 'Microchip MRF24J40'
+    desc = 'IEEE 802.15.4 2.4 GHz RF tranceiver chip.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['mrf24j40']
+    annotations = (
+        ('sread', 'Short register read commands'),
+        ('swrite', 'Short register write commands'),
+        ('lread', 'Long register read commands'),
+        ('lwrite', 'Long register write commands'),
+        ('warning', 'Warnings'),
+    )
+    annotation_rows = (
+        ('read', 'Read', (0, 2)),
+        ('write', 'Write', (1, 3)),
+        ('warnings', 'Warnings', (4,)),
+    )
+
+    def __init__(self):
+        self.ss_cmd, self.es_cmd = 0, 0
+        self.mosi_bytes = []
+        self.miso_bytes = []
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putx(self, data):
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
+
+    def putw(self, pos, msg):
+        self.put(pos[0], pos[1], self.out_ann, [4, [msg]])
+
+    def reset(self):
+        self.mosi_bytes = []
+        self.miso_bytes = []
+
+    def handle_short(self):
+        write = self.mosi_bytes[0] & 0x1
+        reg = (self.mosi_bytes[0] >> 1) & 0x3f
+        reg_desc = sregs.get(reg, 'illegal')
+        if write:
+            self.putx([1, ['%s: %#x' % (reg_desc, self.mosi_bytes[1])]])
+        else:
+            self.putx([0, ['%s: %#x' % (reg_desc, self.miso_bytes[1])]])
+
+    def handle_long(self):
+        dword = self.mosi_bytes[0] << 8 | self.mosi_bytes[1]
+        write = dword & (0x1 << 4)
+        reg = dword >> 5 & 0x3ff
+        if reg >= 0x0:
+            reg_desc = 'TX:%#x' % reg
+        if reg >= 0x80:
+            reg_desc = 'TX beacon:%#x' % reg
+        if reg >= 0x100:
+            reg_desc = 'TX GTS1:%#x' % reg
+        if reg >= 0x180:
+            reg_desc = 'TX GTS2:%#x' % reg
+        if reg >= 0x200:
+            reg_desc = lregs.get(reg, 'illegal')
+        if reg >= 0x280:
+            reg_desc = 'Security keys:%#x' % reg
+        if reg >= 0x2c0:
+            reg_desc = 'Reserved:%#x' % reg
+        if reg >= 0x300:
+            reg_desc = 'RX:%#x' % reg
+
+        if write:
+            self.putx([3, ['%s: %#x' % (reg_desc, self.mosi_bytes[2])]])
+        else:
+            self.putx([2, ['%s: %#x' % (reg_desc, self.miso_bytes[2])]])
+
+    def decode(self, ss, es, data):
+        ptype = data[0]
+        if ptype == 'CS-CHANGE':
+            # If we transition high mid-stream, toss out our data and restart.
+            cs_old, cs_new = data[1:]
+            if cs_old is not None and cs_old == 0 and cs_new == 1:
+                if len(self.mosi_bytes) not in (0, 2, 3):
+                    self.putw([self.ss_cmd, es], 'Misplaced CS!')
+                    self.reset()
+            return
+
+        # Don't care about anything else.
+        if ptype != 'DATA':
+            return
+        mosi, miso = data[1:]
+
+        self.ss, self.es = ss, es
+
+        if len(self.mosi_bytes) == 0:
+            self.ss_cmd = ss
+        self.mosi_bytes.append(mosi)
+        self.miso_bytes.append(miso)
+
+        # Everything is either 2 bytes or 3 bytes.
+        if len(self.mosi_bytes) < 2:
+            return
+
+        if self.mosi_bytes[0] & 0x80:
+            if len(self.mosi_bytes) == 3:
+                self.es_cmd = es
+                self.handle_long()
+                self.reset()
+        else:
+            self.es_cmd = es
+            self.handle_short()
+            self.reset()
diff --git a/decoders/mx25lxx05d/pd.py b/decoders/mx25lxx05d/pd.py
deleted file mode 100644
index a6c72d8..0000000
--- a/decoders/mx25lxx05d/pd.py
+++ /dev/null
@@ -1,375 +0,0 @@
-##
-## This file is part of the libsigrokdecode project.
-##
-## Copyright (C) 2011-2014 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
-##
-
-import sigrokdecode as srd
-
-# Dict which maps command IDs to their names and descriptions.
-cmds = {
-    0x06: ('WREN', 'Write enable'),
-    0x04: ('WRDI', 'Write disable'),
-    0x9f: ('RDID', 'Read identification'),
-    0x05: ('RDSR', 'Read status register'),
-    0x01: ('WRSR', 'Write status register'),
-    0x03: ('READ', 'Read data'),
-    0x0b: ('FAST/READ', 'Fast read data'),
-    0xbb: ('2READ', '2x I/O read'),
-    0x20: ('SE', 'Sector erase'),
-    0xd8: ('BE', 'Block erase'),
-    0x60: ('CE', 'Chip erase'),
-    0xc7: ('CE2', 'Chip erase'), # Alternative command ID
-    0x02: ('PP', 'Page program'),
-    0xad: ('CP', 'Continuously program mode'),
-    0xb9: ('DP', 'Deep power down'),
-    0xab: ('RDP/RES', 'Release from deep powerdown / Read electronic ID'),
-    0x90: ('REMS', 'Read electronic manufacturer & device ID'),
-    0xef: ('REMS2', 'Read ID for 2x I/O mode'),
-    0xb1: ('ENSO', 'Enter secured OTP'),
-    0xc1: ('EXSO', 'Exit secured OTP'),
-    0x2b: ('RDSCUR', 'Read security register'),
-    0x2f: ('WRSCUR', 'Write security register'),
-    0x70: ('ESRY', 'Enable SO to output RY/BY#'),
-    0x80: ('DSRY', 'Disable SO to output RY/BY#'),
-}
-
-device_name = {
-    0x14: 'MX25L1605D',
-    0x15: 'MX25L3205D',
-    0x16: 'MX25L6405D',
-}
-
-def cmd_annotation_classes():
-    return tuple([tuple([cmd[0].lower(), cmd[1]]) for cmd in cmds.values()])
-
-def decode_status_reg(data):
-    # TODO: Additional per-bit(s) self.put() calls with correct start/end.
-
-    # Bits[0:0]: WIP (write in progress)
-    s = 'W' if (data & (1 << 0)) else 'No w'
-    ret = '%srite operation in progress.\n' % s
-
-    # Bits[1:1]: WEL (write enable latch)
-    s = '' if (data & (1 << 1)) else 'not '
-    ret += 'Internal write enable latch is %sset.\n' % s
-
-    # Bits[5:2]: Block protect bits
-    # TODO: More detailed decoding (chip-dependent).
-    ret += 'Block protection bits (BP3-BP0): 0x%x.\n' % ((data & 0x3c) >> 2)
-
-    # Bits[6:6]: Continuously program mode (CP mode)
-    s = '' if (data & (1 << 6)) else 'not '
-    ret += 'Device is %sin continuously program mode (CP mode).\n' % s
-
-    # Bits[7:7]: SRWD (status register write disable)
-    s = 'not ' if (data & (1 << 7)) else ''
-    ret += 'Status register writes are %sallowed.\n' % s
-
-    return ret
-
-class Decoder(srd.Decoder):
-    api_version = 2
-    id = 'mx25lxx05d'
-    name = 'MX25Lxx05D'
-    longname = 'Macronix MX25Lxx05D'
-    desc = 'SPI (NOR) flash chip protocol.'
-    license = 'gplv2+'
-    inputs = ['logic']
-    outputs = ['mx25lxx05d']
-    annotations = cmd_annotation_classes() + (
-        ('bits', 'Bits'),
-        ('bits2', 'Bits2'),
-        ('warnings', 'Warnings'),
-    )
-    annotation_rows = (
-        ('bits', 'Bits', (24, 25)),
-        ('commands', 'Commands', tuple(range(23 + 1))),
-        ('warnings', 'Warnings', (26,)),
-    )
-
-    def __init__(self, **kwargs):
-        self.state = None
-        self.cmdstate = 1
-        self.addr = 0
-        self.data = []
-
-    def start(self):
-        self.out_ann = self.register(srd.OUTPUT_ANN)
-
-    def putx(self, data):
-        # Simplification, most annotations span exactly one SPI byte/packet.
-        self.put(self.ss, self.es, self.out_ann, data)
-
-    def handle_wren(self, mosi, miso):
-        self.putx([0, ['Command: %s' % cmds[self.state][1]]])
-        self.state = None
-
-    def handle_wrdi(self, mosi, miso):
-        pass # TODO
-
-    # TODO: Check/display device ID / name
-    def handle_rdid(self, mosi, miso):
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.start_sample = self.ss
-            self.putx([2, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate == 2:
-            # Byte 2: Slave sends the JEDEC manufacturer ID.
-            self.putx([2, ['Manufacturer ID: 0x%02x' % miso]])
-        elif self.cmdstate == 3:
-            # Byte 3: Slave sends the memory type (0x20 for this chip).
-            self.putx([2, ['Memory type: 0x%02x' % miso]])
-        elif self.cmdstate == 4:
-            # Byte 4: Slave sends the device ID.
-            self.device_id = miso
-            self.putx([2, ['Device ID: 0x%02x' % miso]])
-
-        if self.cmdstate == 4:
-            # TODO: Check self.device_id is valid & exists in device_names.
-            # TODO: Same device ID? Check!
-            d = 'Device: Macronix %s' % device_name[self.device_id]
-            self.put(self.start_sample, self.es, self.out_ann, [0, [d]])
-            self.state = None
-        else:
-            self.cmdstate += 1
-
-    def handle_rdsr(self, mosi, miso):
-        # Read status register: Master asserts CS#, sends RDSR command,
-        # reads status register byte. If CS# is kept asserted, the status
-        # register can be read continuously / multiple times in a row.
-        # When done, the master de-asserts CS# again.
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.putx([3, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate >= 2:
-            # Bytes 2-x: Slave sends status register as long as master clocks.
-            if self.cmdstate <= 3: # TODO: While CS# asserted.
-                self.putx([24, ['Status register: 0x%02x' % miso]])
-                self.putx([25, [decode_status_reg(miso)]])
-
-            if self.cmdstate == 3: # TODO: If CS# got de-asserted.
-                self.state = None
-                return
-
-        self.cmdstate += 1
-
-    def handle_wrsr(self, mosi, miso):
-        pass # TODO
-
-    def handle_read(self, mosi, miso):
-        # Read data bytes: Master asserts CS#, sends READ command, sends
-        # 3-byte address, reads >= 1 data bytes, de-asserts CS#.
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.putx([5, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate in (2, 3, 4):
-            # Bytes 2/3/4: Master sends read address (24bits, MSB-first).
-            self.addr |= (mosi << ((4 - self.cmdstate) * 8))
-            # self.putx([0, ['Read address, byte %d: 0x%02x' % \
-            #                (4 - self.cmdstate, mosi)]])
-            if self.cmdstate == 4:
-                self.putx([24, ['Read address: 0x%06x' % self.addr]])
-                self.addr = 0
-        elif self.cmdstate >= 5:
-            # Bytes 5-x: Master reads data bytes (until CS# de-asserted).
-            # TODO: For now we hardcode 256 bytes per READ command.
-            if self.cmdstate <= 256 + 4: # TODO: While CS# asserted.
-                self.data.append(miso)
-                # self.putx([0, ['New read byte: 0x%02x' % miso]])
-
-            if self.cmdstate == 256 + 4: # TODO: If CS# got de-asserted.
-                # s = ', '.join(map(hex, self.data))
-                s = ''.join(map(chr, self.data))
-                self.putx([24, ['Read data']])
-                self.putx([25, ['Read data: %s' % s]])
-                self.data = []
-                self.state = None
-                return
-
-        self.cmdstate += 1
-
-    def handle_fast_read(self, mosi, miso):
-        pass # TODO
-
-    def handle_2read(self, mosi, miso):
-        pass # TODO
-
-    # TODO: Warn/abort if we don't see the necessary amount of bytes.
-    # TODO: Warn if WREN was not seen before.
-    def handle_se(self, mosi, miso):
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.addr = 0
-            self.start_sample = self.ss
-            self.putx([8, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate in (2, 3, 4):
-            # Bytes 2/3/4: Master sends sectror address (24bits, MSB-first).
-            self.addr |= (mosi << ((4 - self.cmdstate) * 8))
-            # self.putx([0, ['Sector address, byte %d: 0x%02x' % \
-            #                (4 - self.cmdstate, mosi)]])
-
-        if self.cmdstate == 4:
-            d = 'Erase sector %d (0x%06x)' % (self.addr, self.addr)
-            self.put(self.start_sample, self.es, self.out_ann, [24, [d]])
-            # TODO: Max. size depends on chip, check that too if possible.
-            if self.addr % 4096 != 0:
-                # Sector addresses must be 4K-aligned (same for all 3 chips).
-                d = 'Warning: Invalid sector address!'
-                self.put(self.start_sample, self.es, self.out_ann, [101, [d]])
-            self.state = None
-        else:
-            self.cmdstate += 1
-
-    def handle_be(self, mosi, miso):
-        pass # TODO
-
-    def handle_ce(self, mosi, miso):
-        pass # TODO
-
-    def handle_ce2(self, mosi, miso):
-        pass # TODO
-
-    def handle_pp(self, mosi, miso):
-        # Page program: Master asserts CS#, sends PP command, sends 3-byte
-        # page address, sends >= 1 data bytes, de-asserts CS#.
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.putx([12, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate in (2, 3, 4):
-            # Bytes 2/3/4: Master sends page address (24bits, MSB-first).
-            self.addr |= (mosi << ((4 - self.cmdstate) * 8))
-            # self.putx([0, ['Page address, byte %d: 0x%02x' % \
-            #                (4 - self.cmdstate, mosi)]])
-            if self.cmdstate == 4:
-                self.putx([24, ['Page address: 0x%06x' % self.addr]])
-                self.addr = 0
-        elif self.cmdstate >= 5:
-            # Bytes 5-x: Master sends data bytes (until CS# de-asserted).
-            # TODO: For now we hardcode 256 bytes per page / PP command.
-            if self.cmdstate <= 256 + 4: # TODO: While CS# asserted.
-                self.data.append(mosi)
-                # self.putx([0, ['New data byte: 0x%02x' % mosi]])
-
-            if self.cmdstate == 256 + 4: # TODO: If CS# got de-asserted.
-                # s = ', '.join(map(hex, self.data))
-                s = ''.join(map(chr, self.data))
-                self.putx([24, ['Page data']])
-                self.putx([25, ['Page data: %s' % s]])
-                self.data = []
-                self.state = None
-                return
-
-        self.cmdstate += 1
-
-    def handle_cp(self, mosi, miso):
-        pass # TODO
-
-    def handle_dp(self, mosi, miso):
-        pass # TODO
-
-    def handle_rdp_res(self, mosi, miso):
-        pass # TODO
-
-    def handle_rems(self, mosi, miso):
-        if self.cmdstate == 1:
-            # Byte 1: Master sends command ID.
-            self.start_sample = self.ss
-            self.putx([16, ['Command: %s' % cmds[self.state][1]]])
-        elif self.cmdstate in (2, 3):
-            # Bytes 2/3: Master sends two dummy bytes.
-            # TODO: Check dummy bytes? Check reply from device?
-            self.putx([24, ['Dummy byte: %s' % mosi]])
-        elif self.cmdstate == 4:
-            # Byte 4: Master sends 0x00 or 0x01.
-            # 0x00: Master wants manufacturer ID as first reply byte.
-            # 0x01: Master wants device ID as first reply byte.
-            self.manufacturer_id_first = True if (mosi == 0x00) else False
-            d = 'manufacturer' if (mosi == 0x00) else 'device'
-            self.putx([24, ['Master wants %s ID first' % d]])
-        elif self.cmdstate == 5:
-            # Byte 5: Slave sends manufacturer ID (or device ID).
-            self.ids = [miso]
-            d = 'Manufacturer' if self.manufacturer_id_first else 'Device'
-            self.putx([24, ['%s ID' % d]])
-        elif self.cmdstate == 6:
-            # Byte 6: Slave sends device ID (or manufacturer ID).
-            self.ids.append(miso)
-            d = 'Manufacturer' if self.manufacturer_id_first else 'Device'
-            self.putx([24, ['%s ID' % d]])
-
-        if self.cmdstate == 6:
-            self.end_sample = self.es
-            id = self.ids[1] if self.manufacturer_id_first else self.ids[0]
-            self.putx([24, ['Device: Macronix %s' % device_name[id]]])
-            self.state = None
-        else:
-            self.cmdstate += 1
-
-    def handle_rems2(self, mosi, miso):
-        pass # TODO
-
-    def handle_enso(self, mosi, miso):
-        pass # TODO
-
-    def handle_exso(self, mosi, miso):
-        pass # TODO
-
-    def handle_rdscur(self, mosi, miso):
-        pass # TODO
-
-    def handle_wrscur(self, mosi, miso):
-        pass # TODO
-
-    def handle_esry(self, mosi, miso):
-        pass # TODO
-
-    def handle_dsry(self, mosi, miso):
-        pass # TODO
-
-    def decode(self, ss, es, data):
-
-        ptype, mosi, miso = data
-
-        # if ptype == 'DATA':
-        #     self.putx([0, ['MOSI: 0x%02x, MISO: 0x%02x' % (mosi, miso)]])
-
-        # if ptype == 'CS-CHANGE':
-        #     if mosi == 1 and miso == 0:
-        #         self.putx([0, ['Asserting CS#']])
-        #     elif mosi == 0 and miso == 1:
-        #         self.putx([0, ['De-asserting CS#']])
-
-        if ptype != 'DATA':
-            return
-
-        self.ss, self.es = ss, es
-
-        # If we encountered a known chip command, enter the resp. state.
-        if self.state == None:
-            self.state = mosi
-            self.cmdstate = 1
-
-        # Handle commands.
-        if self.state in cmds:
-            s = 'handle_%s' % cmds[self.state][0].lower().replace('/', '_')
-            handle_reg = getattr(self, s)
-            handle_reg(mosi, miso)
-        else:
-            self.putx([24, ['Unknown command: 0x%02x' % mosi]])
-            self.state = None
-
diff --git a/decoders/mxc6225xu/__init__.py b/decoders/mxc6225xu/__init__.py
index c4209c8..daeb89e 100644
--- a/decoders/mxc6225xu/__init__.py
+++ b/decoders/mxc6225xu/__init__.py
@@ -26,5 +26,4 @@ The chip's I²C interface supports standard mode and fast mode (max. 400kHz).
 Its I²C slave address is 0x2a.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/mxc6225xu/pd.py b/decoders/mxc6225xu/pd.py
index e0c857f..832eb06 100644
--- a/decoders/mxc6225xu/pd.py
+++ b/decoders/mxc6225xu/pd.py
@@ -72,7 +72,7 @@ class Decoder(srd.Decoder):
         ('text', 'Human-readable text'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
 
     def start(self):
@@ -97,7 +97,7 @@ class Decoder(srd.Decoder):
         # Bits[7:7]: INT
         int_val = (b >> 7) & 1
         s = 'unchanged and no' if (int_val == 0) else 'changed or'
-        ann = 'INT = %d: Orientation %s shake event occured\n' % (int_val, s)
+        ann = 'INT = %d: Orientation %s shake event occurred\n' % (int_val, s)
 
         # Bits[6:5]: SH[1:0]
         sh = (((b >> 6) & 1) << 1) | ((b >> 5) & 1)
@@ -165,7 +165,6 @@ class Decoder(srd.Decoder):
             if cmd != 'START':
                 return
             self.state = 'GET SLAVE ADDR'
-            self.block_start_sample = ss
         elif self.state == 'GET SLAVE ADDR':
             # Wait for an address write operation.
             # TODO: We should only handle packets to the slave(?)
@@ -213,6 +212,3 @@ class Decoder(srd.Decoder):
                 self.state = 'IDLE'
             else:
                 pass # TODO?
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/dcf77/__init__.py b/decoders/nrf24l01/__init__.py
similarity index 68%
copy from decoders/dcf77/__init__.py
copy to decoders/nrf24l01/__init__.py
index 04805c2..7b4d748 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/nrf24l01/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Jens Steinhauser <jens.steinhauser at gmail.com>
 ##
 ## 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
@@ -19,12 +19,12 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This decoder stacks on top of the 'spi' PD and decodes the protocol spoken
+by the Nordic Semiconductor nRF24L01 and nRF24L01+ 2.4GHz transceiver chips.
 
 Details:
-http://en.wikipedia.org/wiki/DCF77
+http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01
+http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01P
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/nrf24l01/pd.py b/decoders/nrf24l01/pd.py
new file mode 100644
index 0000000..d46eea4
--- /dev/null
+++ b/decoders/nrf24l01/pd.py
@@ -0,0 +1,329 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Jens Steinhauser <jens.steinhauser at gmail.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class ChannelError(Exception):
+    pass
+
+regs = {
+#   addr: ('name',        size)
+    0x00: ('CONFIG',      1),
+    0x01: ('EN_AA',       1),
+    0x02: ('EN_RXADDR',   1),
+    0x03: ('SETUP_AW',    1),
+    0x04: ('SETUP_RETR',  1),
+    0x05: ('RF_CH',       1),
+    0x06: ('RF_SETUP',    1),
+    0x07: ('STATUS',      1),
+    0x08: ('OBSERVE_TX',  1),
+    0x09: ('RPD',         1),
+    0x0a: ('RX_ADDR_P0',  5),
+    0x0b: ('RX_ADDR_P1',  5),
+    0x0c: ('RX_ADDR_P2',  1),
+    0x0d: ('RX_ADDR_P3',  1),
+    0x0e: ('RX_ADDR_P4',  1),
+    0x0f: ('RX_ADDR_P5',  1),
+    0x10: ('TX_ADDR',     5),
+    0x11: ('RX_PW_P0',    1),
+    0x12: ('RX_PW_P1',    1),
+    0x13: ('RX_PW_P2',    1),
+    0x14: ('RX_PW_P3',    1),
+    0x15: ('RX_PW_P4',    1),
+    0x16: ('RX_PW_P5',    1),
+    0x17: ('FIFO_STATUS', 1),
+    0x1c: ('DYNPD',       1),
+    0x1d: ('FEATURE',     1),
+}
+
+xn297_regs = {
+    0x19: ('DEMOD_CAL',   5),
+    0x1e: ('RF_CAL',      7),
+    0x1f: ('BB_CAL',      5),
+}
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'nrf24l01'
+    name = 'nRF24L01(+)'
+    longname = 'Nordic Semiconductor nRF24L01/nRF24L01+'
+    desc = '2.4GHz transceiver chip.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['nrf24l01']
+    options = (
+        {'id': 'chip', 'desc': 'Chip type',
+            'default': 'nrf24l01', 'values': ('nrf24l01', 'xn297')},
+    )
+    annotations = (
+        # Sent from the host to the chip.
+        ('cmd', 'Commands sent to the device'),
+        ('tx-data', 'Payload sent to the device'),
+
+        # Returned by the chip.
+        ('register', 'Registers read from the device'),
+        ('rx-data', 'Payload read from the device'),
+
+        ('warning', 'Warnings'),
+    )
+    ann_cmd = 0
+    ann_tx = 1
+    ann_reg = 2
+    ann_rx = 3
+    ann_warn = 4
+    annotation_rows = (
+        ('commands', 'Commands', (ann_cmd, ann_tx)),
+        ('responses', 'Responses', (ann_reg, ann_rx)),
+        ('warnings', 'Warnings', (ann_warn,)),
+    )
+
+    def __init__(self):
+        self.next()
+        self.requirements_met = True
+        self.cs_was_released = False
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        if self.options['chip'] == 'xn297':
+            regs.update(xn297_regs)
+
+    def warn(self, pos, msg):
+        '''Put a warning message 'msg' at 'pos'.'''
+        self.put(pos[0], pos[1], self.out_ann, [self.ann_warn, [msg]])
+
+    def putp(self, pos, ann, msg):
+        '''Put an annotation message 'msg' at 'pos'.'''
+        self.put(pos[0], pos[1], self.out_ann, [ann, [msg]])
+
+    def next(self):
+        '''Resets the decoder after a complete command was decoded.'''
+        # 'True' for the first byte after CS went low.
+        self.first = True
+
+        # The current command, and the minimum and maximum number
+        # of data bytes to follow.
+        self.cmd = None
+        self.min = 0
+        self.max = 0
+
+        # Used to collect the bytes after the command byte
+        # (and the start/end sample number).
+        self.mb = []
+        self.mb_s = -1
+        self.mb_e = -1
+
+    def mosi_bytes(self):
+        '''Returns the collected MOSI bytes of a multi byte command.'''
+        return [b[0] for b in self.mb]
+
+    def miso_bytes(self):
+        '''Returns the collected MISO bytes of a multi byte command.'''
+        return [b[1] for b in self.mb]
+
+    def decode_command(self, pos, b):
+        '''Decodes the command byte 'b' at position 'pos' and prepares
+        the decoding of the following data bytes.'''
+        c = self.parse_command(b)
+        if c is None:
+            self.warn(pos, 'unknown command')
+            return
+
+        self.cmd, self.dat, self.min, self.max = c
+
+        if self.cmd in ('W_REGISTER', 'ACTIVATE'):
+            # Don't output anything now, the command is merged with
+            # the data bytes following it.
+            self.mb_s = pos[0]
+        else:
+            self.putp(pos, self.ann_cmd, self.format_command())
+
+    def format_command(self):
+        '''Returns the label for the current command.'''
+        if self.cmd == 'R_REGISTER':
+            reg = regs[self.dat][0] if self.dat in regs else 'unknown register'
+            return 'Cmd R_REGISTER "{}"'.format(reg)
+        else:
+            return 'Cmd {}'.format(self.cmd)
+
+    def parse_command(self, b):
+        '''Parses the command byte.
+
+        Returns a tuple consisting of:
+        - the name of the command
+        - additional data needed to dissect the following bytes
+        - minimum number of following bytes
+        - maximum number of following bytes
+        '''
+
+        if (b & 0xe0) in (0b00000000, 0b00100000):
+            c = 'R_REGISTER' if not (b & 0xe0) else 'W_REGISTER'
+            d = b & 0x1f
+            m = regs[d][1] if d in regs else 1
+            return (c, d, 1, m)
+        if b == 0b01010000:
+            # nRF24L01 only
+            return ('ACTIVATE', None, 1, 1)
+        if b == 0b01100001:
+            return ('R_RX_PAYLOAD', None, 1, 32)
+        if b == 0b01100000:
+            return ('R_RX_PL_WID', None, 1, 1)
+        if b == 0b10100000:
+            return ('W_TX_PAYLOAD', None, 1, 32)
+        if b == 0b10110000:
+            return ('W_TX_PAYLOAD_NOACK', None, 1, 32)
+        if (b & 0xf8) == 0b10101000:
+            return ('W_ACK_PAYLOAD', b & 0x07, 1, 32)
+        if b == 0b11100001:
+            return ('FLUSH_TX', None, 0, 0)
+        if b == 0b11100010:
+            return ('FLUSH_RX', None, 0, 0)
+        if b == 0b11100011:
+            return ('REUSE_TX_PL', None, 0, 0)
+        if b == 0b11111111:
+            return ('NOP', None, 0, 0)
+
+    def decode_register(self, pos, ann, regid, data):
+        '''Decodes a register.
+
+        pos   -- start and end sample numbers of the register
+        ann   -- is the annotation number that is used to output the register.
+        regid -- may be either an integer used as a key for the 'regs'
+                 dictionary, or a string directly containing a register name.'
+        data  -- is the register content.
+        '''
+
+        if type(regid) == int:
+            # Get the name of the register.
+            if regid not in regs:
+                self.warn(pos, 'unknown register')
+                return
+            name = regs[regid][0]
+        else:
+            name = regid
+
+        # Multi byte register come LSByte first.
+        data = reversed(data)
+
+        if self.cmd == 'W_REGISTER' and ann == self.ann_cmd:
+            # The 'W_REGISTER' command is merged with the following byte(s).
+            label = '{}: {}'.format(self.format_command(), name)
+        else:
+            label = 'Reg {}'.format(name)
+
+        self.decode_mb_data(pos, ann, data, label, True)
+
+    def decode_mb_data(self, pos, ann, data, label, always_hex):
+        '''Decodes the data bytes 'data' of a multibyte command at position
+        'pos'. The decoded data is prefixed with 'label'. If 'always_hex' is
+        True, all bytes are decoded as hex codes, otherwise only non
+        printable characters are escaped.'''
+
+        if always_hex:
+            def escape(b):
+                return '{:02X}'.format(b)
+        else:
+            def escape(b):
+                c = chr(b)
+                if not str.isprintable(c):
+                    return '\\x{:02X}'.format(b)
+                return c
+
+        data = ''.join([escape(b) for b in data])
+        text = '{} = "{}"'.format(label, data)
+        self.putp(pos, ann, text)
+
+    def finish_command(self, pos):
+        '''Decodes the remaining data bytes at position 'pos'.'''
+
+        if self.cmd == 'R_REGISTER':
+            self.decode_register(pos, self.ann_reg,
+                                 self.dat, self.miso_bytes())
+        elif self.cmd == 'W_REGISTER':
+            self.decode_register(pos, self.ann_cmd,
+                                 self.dat, self.mosi_bytes())
+        elif self.cmd == 'R_RX_PAYLOAD':
+            self.decode_mb_data(pos, self.ann_rx,
+                                self.miso_bytes(), 'RX payload', False)
+        elif (self.cmd == 'W_TX_PAYLOAD' or
+              self.cmd == 'W_TX_PAYLOAD_NOACK'):
+            self.decode_mb_data(pos, self.ann_tx,
+                                self.mosi_bytes(), 'TX payload', False)
+        elif self.cmd == 'W_ACK_PAYLOAD':
+            lbl = 'ACK payload for pipe {}'.format(self.dat)
+            self.decode_mb_data(pos, self.ann_tx,
+                                self.mosi_bytes(), lbl, False)
+        elif self.cmd == 'R_RX_PL_WID':
+            msg = 'Payload width = {}'.format(self.mb[0][1])
+            self.putp(pos, self.ann_reg, msg)
+        elif self.cmd == 'ACTIVATE':
+            self.putp(pos, self.ann_cmd, self.format_command())
+            if self.mosi_bytes()[0] != 0x73:
+                self.warn(pos, 'wrong data for "ACTIVATE" command')
+
+    def decode(self, ss, es, data):
+        if not self.requirements_met:
+            return
+
+        ptype, data1, data2 = data
+
+        if ptype == 'CS-CHANGE':
+            if data1 is None:
+                if data2 is None:
+                    self.requirements_met = False
+                    raise ChannelError('CS# pin required.')
+                elif data2 == 1:
+                    self.cs_was_released = True
+
+            if data1 == 0 and data2 == 1:
+                # Rising edge, the complete command is transmitted, process
+                # the bytes that were send after the command byte.
+                if self.cmd:
+                    # Check if we got the minimum number of data bytes
+                    # after the command byte.
+                    if len(self.mb) < self.min:
+                        self.warn((ss, ss), 'missing data bytes')
+                    elif self.mb:
+                        self.finish_command((self.mb_s, self.mb_e))
+
+                self.next()
+                self.cs_was_released = True
+        elif ptype == 'DATA' and self.cs_was_released:
+            mosi, miso = data1, data2
+            pos = (ss, es)
+
+            if miso is None or mosi is None:
+                self.requirements_met = False
+                raise ChannelError('Both MISO and MOSI pins required.')
+
+            if self.first:
+                self.first = False
+                # First MOSI byte is always the command.
+                self.decode_command(pos, mosi)
+                # First MISO byte is always the status register.
+                self.decode_register(pos, self.ann_reg, 'STATUS', [miso])
+            else:
+                if not self.cmd or len(self.mb) >= self.max:
+                    self.warn(pos, 'excess byte')
+                else:
+                    # Collect the bytes after the command byte.
+                    if self.mb_s == -1:
+                        self.mb_s = ss
+                    self.mb_e = es
+                    self.mb.append((mosi, miso))
diff --git a/decoders/nunchuk/__init__.py b/decoders/nunchuk/__init__.py
index 2fdaaeb..c579145 100644
--- a/decoders/nunchuk/__init__.py
+++ b/decoders/nunchuk/__init__.py
@@ -28,5 +28,4 @@ http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/
 https://www.sparkfun.com/products/9281
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/nunchuk/pd.py b/decoders/nunchuk/pd.py
index 95d7bdb..48a7099 100644
--- a/decoders/nunchuk/pd.py
+++ b/decoders/nunchuk/pd.py
@@ -47,12 +47,12 @@ class Decoder(srd.Decoder):
         ('warnings', 'Warnings', (14,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.sx = self.sy = self.ax = self.ay = self.az = self.bz = self.bc = -1
         self.databytecount = 0
         self.reg = 0x00
-        self.ss = self.es = self.block_ss = self.block_es = 0
+        self.ss = self.es = self.ss_block = self.es_block = 0
         self.init_seq = []
 
     def start(self):
@@ -62,13 +62,13 @@ class Decoder(srd.Decoder):
         self.put(self.ss, self.es, self.out_ann, data)
 
     def putb(self, data):
-        self.put(self.block_ss, self.block_es, self.out_ann, data)
+        self.put(self.ss_block, self.es_block, self.out_ann, data)
 
     def putd(self, bit1, bit2, data):
         self.put(self.bits[bit1][1], self.bits[bit2][2], self.out_ann, data)
 
     def handle_reg_0x00(self, databyte):
-        self.block_ss = self.ss
+        self.ss_block = self.ss
         self.sx = databyte
         self.putx([0, ['Analog stick X position: 0x%02X' % self.sx,
                        'SX: 0x%02X' % self.sx]])
@@ -94,7 +94,7 @@ class Decoder(srd.Decoder):
                        'AZ[9:2]: 0x%03X' % self.az]])
 
     def handle_reg_0x05(self, databyte):
-        self.block_es = self.es
+        self.es_block = self.es
         self.bz = (databyte & (1 << 0)) >> 0 # Bits[0:0]
         self.bc = (databyte & (1 << 1)) >> 1 # Bits[1:1]
         ax_rest = (databyte & (3 << 2)) >> 2 # Bits[3:2]
@@ -128,8 +128,8 @@ class Decoder(srd.Decoder):
         t = (self.sx, self.sy, self.ax, self.ay, self.az, self.bz, self.bc)
         if -1 in t:
             return
-        bz = 'pressed' if self.bz == 1 else 'not pressed'
-        bc = 'pressed' if self.bc == 1 else 'not pressed'
+        bz = 'pressed' if self.bz == 0 else 'not pressed'
+        bc = 'pressed' if self.bc == 0 else 'not pressed'
         s = 'Analog stick: %d/%d, accelerometer: %d/%d/%d, Z: %s, C: %s' % \
             (self.sx, self.sy, self.ax, self.ay, self.az, bz, bc)
         self.putb([13, [s]])
@@ -170,7 +170,7 @@ class Decoder(srd.Decoder):
             if cmd != 'START':
                 return
             self.state = 'GET SLAVE ADDR'
-            self.block_start_sample = ss
+            self.ss_block = ss
         elif self.state == 'GET SLAVE ADDR':
             # Wait for an address read/write operation.
             if cmd == 'ADDRESS READ':
@@ -183,7 +183,7 @@ class Decoder(srd.Decoder):
                 handle_reg(databyte)
                 self.reg += 1
             elif cmd == 'STOP':
-                self.block_end_sample = es
+                self.es_block = es
                 self.output_full_block_if_possible()
                 self.sx = self.sy = self.ax = self.ay = self.az = -1
                 self.bz = self.bc = -1
@@ -195,13 +195,10 @@ class Decoder(srd.Decoder):
             if cmd == 'DATA WRITE':
                 self.handle_reg_write(databyte)
             elif cmd == 'STOP':
-                self.block_end_sample = es
+                self.es_block = es
                 self.output_init_seq()
                 self.init_seq = []
                 self.state = 'IDLE'
             else:
                 # self.putx([14, ['Ignoring: %s (data=%s)' % (cmd, databyte)]])
                 pass
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/onewire_link/__init__.py b/decoders/onewire_link/__init__.py
index d153f93..12aad25 100644
--- a/decoders/onewire_link/__init__.py
+++ b/decoders/onewire_link/__init__.py
@@ -65,5 +65,4 @@ These options should be configured only on very rare cases and the user should
 read the decoder source code to understand them correctly.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/onewire_link/pd.py b/decoders/onewire_link/pd.py
index 3641b98..bd64aa1 100644
--- a/decoders/onewire_link/pd.py
+++ b/decoders/onewire_link/pd.py
@@ -20,6 +20,9 @@
 
 import sigrokdecode as srd
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'onewire_link'
@@ -90,7 +93,7 @@ class Decoder(srd.Decoder):
     def putrs(self, data):
         self.put(self.rise, self.samplenum, self.out_ann, data)
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.samplenum = 0
         self.state = 'WAIT FOR FALLING EDGE'
@@ -106,11 +109,7 @@ class Decoder(srd.Decoder):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
-    def metadata(self, key, value):
-        if key != srd.SRD_CONF_SAMPLERATE:
-            return
-        self.samplerate = value
-
+    def checks(self):
         # Check if samplerate is appropriate.
         if self.options['overdrive'] == 'yes':
             if self.samplerate < 2000000:
@@ -123,37 +122,10 @@ class Decoder(srd.Decoder):
             if self.samplerate < 400000:
                 self.putm([1, ['Sampling rate is too low. Must be above ' +
                                '400kHz for proper normal mode decoding.']])
-            elif (self.samplerate < 1000000):
+            elif self.samplerate < 1000000:
                 self.putm([1, ['Sampling rate is suggested to be above ' +
                                '1MHz for proper normal mode decoding.']])
 
-        # The default 1-Wire time base is 30us. This is used to calculate
-        # sampling times.
-        samplerate = float(self.samplerate)
-
-        x = float(self.options['cnt_normal_bit']) / 1000000.0
-        self.cnt_normal_bit = int(samplerate * x) - 1
-        x = float(self.options['cnt_normal_slot']) / 1000000.0
-        self.cnt_normal_slot = int(samplerate * x) - 1
-        x = float(self.options['cnt_normal_presence']) / 1000000.0
-        self.cnt_normal_presence = int(samplerate * x) - 1
-        x = float(self.options['cnt_normal_reset']) / 1000000.0
-        self.cnt_normal_reset = int(samplerate * x) - 1
-        x = float(self.options['cnt_overdrive_bit']) / 1000000.0
-        self.cnt_overdrive_bit = int(samplerate * x) - 1
-        x = float(self.options['cnt_overdrive_slot']) / 1000000.0
-        self.cnt_overdrive_slot = int(samplerate * x) - 1
-        x = float(self.options['cnt_overdrive_presence']) / 1000000.0
-        self.cnt_overdrive_presence = int(samplerate * x) - 1
-        x = float(self.options['cnt_overdrive_reset']) / 1000000.0
-        self.cnt_overdrive_reset = int(samplerate * x) - 1
-
-        # Organize values into lists.
-        self.cnt_bit = [self.cnt_normal_bit, self.cnt_overdrive_bit]
-        self.cnt_presence = [self.cnt_normal_presence, self.cnt_overdrive_presence]
-        self.cnt_reset = [self.cnt_normal_reset, self.cnt_overdrive_reset]
-        self.cnt_slot = [self.cnt_normal_slot, self.cnt_overdrive_slot]
-
         # Check if sample times are in the allowed range.
 
         time_min = float(self.cnt_normal_bit) / self.samplerate
@@ -182,12 +154,47 @@ class Decoder(srd.Decoder):
         if (time_min < 0.0000073) or (time_max > 0.000010):
             self.putm([1, ['The overdrive mode presence sample time interval ' +
                  '(%2.1fus-%2.1fus) should be inside (7.3us, 10.0us).'
-                 % (time_min*1000000, time_max*1000000)]])
+                 % (time_min * 1000000, time_max * 1000000)]])
+
+
+    def metadata(self, key, value):
+        if key != srd.SRD_CONF_SAMPLERATE:
+            return
+        self.samplerate = value
+
+        # The default 1-Wire time base is 30us. This is used to calculate
+        # sampling times.
+        samplerate = float(self.samplerate)
+
+        x = float(self.options['cnt_normal_bit']) / 1000000.0
+        self.cnt_normal_bit = int(samplerate * x) - 1
+        x = float(self.options['cnt_normal_slot']) / 1000000.0
+        self.cnt_normal_slot = int(samplerate * x) - 1
+        x = float(self.options['cnt_normal_presence']) / 1000000.0
+        self.cnt_normal_presence = int(samplerate * x) - 1
+        x = float(self.options['cnt_normal_reset']) / 1000000.0
+        self.cnt_normal_reset = int(samplerate * x) - 1
+        x = float(self.options['cnt_overdrive_bit']) / 1000000.0
+        self.cnt_overdrive_bit = int(samplerate * x) - 1
+        x = float(self.options['cnt_overdrive_slot']) / 1000000.0
+        self.cnt_overdrive_slot = int(samplerate * x) - 1
+        x = float(self.options['cnt_overdrive_presence']) / 1000000.0
+        self.cnt_overdrive_presence = int(samplerate * x) - 1
+        x = float(self.options['cnt_overdrive_reset']) / 1000000.0
+        self.cnt_overdrive_reset = int(samplerate * x) - 1
+
+        # Organize values into lists.
+        self.cnt_bit = [self.cnt_normal_bit, self.cnt_overdrive_bit]
+        self.cnt_presence = [self.cnt_normal_presence, self.cnt_overdrive_presence]
+        self.cnt_reset = [self.cnt_normal_reset, self.cnt_overdrive_reset]
+        self.cnt_slot = [self.cnt_normal_slot, self.cnt_overdrive_slot]
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, (owr, pwr)) in data:
+            if self.samplenum == 0:
+                self.checks()
             # State machine.
             if self.state == 'WAIT FOR FALLING EDGE':
                 # The start of a cycle is a falling edge.
@@ -251,10 +258,10 @@ class Decoder(srd.Decoder):
                     # Save the sample number for the rising edge.
                     self.rise = self.samplenum
                     self.putfr([2, ['Reset', 'Rst', 'R']])
-                    self.state = "WAIT FOR PRESENCE DETECT"
+                    self.state = 'WAIT FOR PRESENCE DETECT'
                 # Otherwise this is assumed to be a data bit.
                 else:
-                    self.state = "WAIT FOR FALLING EDGE"
+                    self.state = 'WAIT FOR FALLING EDGE'
             elif self.state == 'WAIT FOR PRESENCE DETECT':
                 # Sample presence status.
                 t = self.samplenum - self.rise
@@ -278,5 +285,3 @@ class Decoder(srd.Decoder):
 
                 # Wait for next slot.
                 self.state = 'WAIT FOR FALLING EDGE'
-            else:
-                raise Exception('Invalid state: %s' % self.state)
diff --git a/decoders/onewire_network/__init__.py b/decoders/onewire_network/__init__.py
index 31e9134..44b9bcc 100644
--- a/decoders/onewire_network/__init__.py
+++ b/decoders/onewire_network/__init__.py
@@ -54,5 +54,4 @@ TODO:
  - Add reporting original/complement address values from the search algorithm.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/onewire_network/pd.py b/decoders/onewire_network/pd.py
index 23402a6..1a7567a 100644
--- a/decoders/onewire_network/pd.py
+++ b/decoders/onewire_network/pd.py
@@ -45,9 +45,9 @@ class Decoder(srd.Decoder):
         ('text', 'Human-readable text'),
     )
 
-    def __init__(self, **kwargs):
-        self.beg = 0
-        self.end = 0
+    def __init__(self):
+        self.ss_block = 0
+        self.es_block = 0
         self.state = 'COMMAND'
         self.bit_cnt = 0
         self.search = 'P'
@@ -62,11 +62,11 @@ class Decoder(srd.Decoder):
 
     def putx(self, data):
         # Helper function for most annotations.
-        self.put(self.beg, self.end, self.out_ann, data)
+        self.put(self.ss_block, self.es_block, self.out_ann, data)
 
     def puty(self, data):
         # Helper function for most protocol packets.
-        self.put(self.beg, self.end, self.out_python, data)
+        self.put(self.ss_block, self.es_block, self.out_python, data)
 
     def decode(self, ss, es, data):
         code, val = data
@@ -126,20 +126,18 @@ class Decoder(srd.Decoder):
             if self.onewire_collect(8, val, ss, es) == 0:
                 return
             self.putx([0, ['ROM error data: 0x%02x' % self.data]])
-        else:
-            raise Exception('Invalid state: %s' % self.state)
 
     # Data collector.
     def onewire_collect(self, length, val, ss, es):
         # Storing the sample this sequence begins with.
         if self.bit_cnt == 1:
-            self.beg = ss
+            self.ss_block = ss
         self.data = self.data & ~(1 << self.bit_cnt) | (val << self.bit_cnt)
         self.bit_cnt += 1
         # Storing the sample this sequence ends with.
         # In case the full length of the sequence is received, return 1.
         if self.bit_cnt == length:
-            self.end = es
+            self.es_block = es
             self.data = self.data & ((1 << length) - 1)
             self.bit_cnt = 0
             return 1
@@ -150,7 +148,7 @@ class Decoder(srd.Decoder):
     def onewire_search(self, length, val, ss, es):
         # Storing the sample this sequence begins with.
         if (self.bit_cnt == 0) and (self.search == 'P'):
-            self.beg = ss
+            self.ss_block = ss
 
         if self.search == 'P':
             # Master receives an original address bit.
@@ -171,7 +169,7 @@ class Decoder(srd.Decoder):
         # Storing the sample this sequence ends with.
         # In case the full length of the sequence is received, return 1.
         if self.bit_cnt == length:
-            self.end = es
+            self.es_block = es
             self.data_p = self.data_p & ((1 << length) - 1)
             self.data_n = self.data_n & ((1 << length) - 1)
             self.data = self.data & ((1 << length) - 1)
diff --git a/decoders/pan1321/__init__.py b/decoders/pan1321/__init__.py
index 9bda523..c14236d 100644
--- a/decoders/pan1321/__init__.py
+++ b/decoders/pan1321/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'uart' PD and decodes the Panasonic PAN1321
 Bluetooth module Serial Port Profile (SPP) protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/pan1321/pd.py b/decoders/pan1321/pd.py
index d173e1c..a8938c6 100644
--- a/decoders/pan1321/pd.py
+++ b/decoders/pan1321/pd.py
@@ -39,7 +39,7 @@ class Decoder(srd.Decoder):
         ('warnings', 'Human-readable warnings'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.cmd = ['', '']
         self.ss_block = None
 
@@ -136,6 +136,9 @@ class Decoder(srd.Decoder):
         if ptype != 'DATA':
             return
 
+        # We're only interested in the byte value (not individual bits).
+        pdata = pdata[0]
+
         # If this is the start of a command/reply, remember the start sample.
         if self.cmd[rxtx] == '':
             self.ss_block = ss
@@ -154,8 +157,5 @@ class Decoder(srd.Decoder):
             self.handle_device_reply(rxtx, self.cmd[rxtx][:-2])
         elif rxtx == TX:
             self.handle_host_command(rxtx, self.cmd[rxtx][:-2])
-        else:
-            raise Exception('Invalid rxtx value: %d' % rxtx)
 
         self.cmd[rxtx] = ''
-
diff --git a/decoders/parallel/__init__.py b/decoders/parallel/__init__.py
index cc1f3d1..a7077bb 100644
--- a/decoders/parallel/__init__.py
+++ b/decoders/parallel/__init__.py
@@ -32,5 +32,4 @@ should be used. Using combinations like D7/D12/D3/D15 is not supported.
 For an 8-bit bus you should use D0-D7, for a 16-bit bus use D0-D15 and so on.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/parallel/pd.py b/decoders/parallel/pd.py
index 03b5e2f..cafaefc 100644
--- a/decoders/parallel/pd.py
+++ b/decoders/parallel/pd.py
@@ -61,6 +61,9 @@ def channel_list(num_channels):
         l.append(d)
     return tuple(l)
 
+class ChannelError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'parallel'
@@ -92,7 +95,6 @@ class Decoder(srd.Decoder):
         self.oldpins = None
         self.ss_item = self.es_item = None
         self.first = True
-        self.state = 'IDLE'
 
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
@@ -123,7 +125,7 @@ class Decoder(srd.Decoder):
         self.items.append(item)
         self.itemcount += 1
 
-        if self.first == True:
+        if self.first:
             # Save the start sample and item for later (no output yet).
             self.ss_item = self.samplenum
             self.first = False
@@ -181,12 +183,10 @@ class Decoder(srd.Decoder):
                 continue
             self.oldpins = pins
 
-            # State machine.
-            if self.state == 'IDLE':
-                if pins[0] not in (0, 1):
-                    self.handle_bits(pins[1:])
-                else:
-                    self.find_clk_edge(pins[0], pins[1:])
-            else:
-                raise Exception('Invalid state: %s' % self.state)
+            if sum(1 for p in pins if p in (0, 1)) == 0:
+                raise ChannelError('At least one channel has to be supplied.')
 
+            if pins[0] not in (0, 1):
+                self.handle_bits(pins[1:])
+            else:
+                self.find_clk_edge(pins[0], pins[1:])
diff --git a/decoders/ir_nec/__init__.py b/decoders/ps2/__init__.py
similarity index 68%
copy from decoders/ir_nec/__init__.py
copy to decoders/ps2/__init__.py
index 84bf428..75c4768 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/ps2/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2016 Daniel Schulte <trilader at schroedingers-bit.net>
 ##
 ## 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
@@ -14,13 +14,13 @@
 ## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+## along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
-'''
+This protocol decoder can decode PS/2 device -> host communication.
 
-from .pd import *
+Host -> device communication is currently not supported.
+'''
 
+from .pd import Decoder
diff --git a/decoders/ps2/pd.py b/decoders/ps2/pd.py
new file mode 100644
index 0000000..6392f1a
--- /dev/null
+++ b/decoders/ps2/pd.py
@@ -0,0 +1,144 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Daniel Schulte <trilader at schroedingers-bit.net>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from collections import namedtuple
+
+class Ann:
+    BIT, START, STOP, PARITY_OK, PARITY_ERR, DATA, WORD = range(7)
+
+Bit = namedtuple('Bit', 'val ss es')
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'ps2'
+    name = 'PS/2'
+    longname = 'PS/2'
+    desc = 'PS/2 keyboard/mouse interface.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['ps2']
+    channels = (
+        {'id': 'clk', 'name': 'Clock', 'desc': 'Clock line'},
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    annotations = (
+        ('bit', 'Bit'),
+        ('start-bit', 'Start bit'),
+        ('stop-bit', 'Stop bit'),
+        ('parity-ok', 'Parity OK bit'),
+        ('parity-err', 'Parity error bit'),
+        ('data-bit', 'Data bit'),
+        ('word', 'Word'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0,)),
+        ('fields', 'Fields', (1, 2, 3, 4, 5, 6)),
+    )
+
+    def __init__(self):
+        self.bits = []
+        self.prev_pins = None
+        self.prev_clock = None
+        self.samplenum = 0
+        self.clock_was_high = False
+        self.bitcount = 0
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putb(self, bit, ann_idx):
+        b = self.bits[bit]
+        self.put(b.ss, b.es, self.out_ann, [ann_idx, [str(b.val)]])
+
+    def putx(self, bit, ann):
+        self.put(self.bits[bit].ss, self.bits[bit].es, self.out_ann, ann)
+
+    def handle_bits(self, datapin):
+        # Ignore non start condition bits (useful during keyboard init).
+        if self.bitcount == 0 and datapin == 1:
+            return
+
+        # Store individual bits and their start/end samplenumbers.
+        self.bits.append(Bit(datapin, self.samplenum, self.samplenum))
+
+        # Fix up end sample numbers of the bits.
+        if self.bitcount > 0:
+            b = self.bits[self.bitcount - 1]
+            self.bits[self.bitcount - 1] = Bit(b.val, b.ss, self.samplenum)
+        if self.bitcount == 11:
+            self.bitwidth = self.bits[1].es - self.bits[2].es
+            b = self.bits[-1]
+            self.bits[-1] = Bit(b.val, b.ss, b.es + self.bitwidth)
+
+        # Find all 11 bits. Start + 8 data + odd parity + stop.
+        if self.bitcount < 11:
+            self.bitcount += 1
+            return
+
+        # Extract data word.
+        word = 0
+        for i in range(8):
+            word |= (self.bits[i + 1].val << i)
+
+        # Calculate parity.
+        parity_ok = (bin(word).count('1') + self.bits[9].val) % 2 == 1
+
+        # Emit annotations.
+        for i in range(11):
+            self.putb(i, Ann.BIT)
+        self.putx(0, [Ann.START, ['Start bit', 'Start', 'S']])
+        self.put(self.bits[1].ss, self.bits[8].es, self.out_ann, [Ann.WORD,
+                 ['Data: %02x' % word, 'D: %02x' % word, '%02x' % word]])
+        if parity_ok:
+            self.putx(9, [Ann.PARITY_OK, ['Parity OK', 'Par OK', 'P']])
+        else:
+            self.putx(9, [Ann.PARITY_ERR, ['Parity error', 'Par err', 'PE']])
+        self.putx(10, [Ann.STOP, ['Stop bit', 'Stop', 'St', 'T']])
+
+        self.bits, self.bitcount = [], 0
+
+    def find_clk_edge(self, clock_pin, data_pin):
+        # Ignore sample if the clock pin hasn't changed.
+        if clock_pin == self.prev_clock:
+            return
+        self.prev_clock = clock_pin
+
+        # Sample on falling clock edge.
+        if clock_pin == 1:
+            return
+
+        # Found the correct clock edge, now get the bits.
+        self.handle_bits(data_pin)
+
+    def decode(self, ss, es, data):
+        for (self.samplenum, pins) in data:
+            clock_pin, data_pin = pins[0], pins[1]
+
+            # Ignore identical samples.
+            if self.prev_pins == pins:
+                continue
+            self.prev_pins = pins
+
+            if clock_pin == 0 and not self.clock_was_high:
+                continue
+            self.clock_was_high = True
+
+            self.find_clk_edge(clock_pin, data_pin)
diff --git a/decoders/ir_nec/__init__.py b/decoders/pwm/__init__.py
similarity index 84%
copy from decoders/ir_nec/__init__.py
copy to decoders/pwm/__init__.py
index 84bf428..096e077 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/pwm/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2014 Torsten Duwe <duwe at suse.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
@@ -19,8 +19,7 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+Pulse-width modulation (a.k.a pulse-duration modulation, PDM) decoder.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/pwm/pd.py b/decoders/pwm/pd.py
new file mode 100644
index 0000000..6ca46b1
--- /dev/null
+++ b/decoders/pwm/pd.py
@@ -0,0 +1,150 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Torsten Duwe <duwe at suse.de>
+## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'pwm'
+    name = 'PWM'
+    longname = 'Pulse-width modulation'
+    desc = 'Analog level encoded in duty cycle percentage.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['pwm']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    options = (
+        {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-high',
+            'values': ('active-low', 'active-high')},
+    )
+    annotations = (
+        ('duty-cycle', 'Duty cycle'),
+        ('period', 'Period'),
+    )
+    annotation_rows = (
+         ('duty-cycle', 'Duty cycle', (0,)),
+         ('period', 'Period', (1,)),
+    )
+    binary = (
+        ('raw', 'RAW file'),
+    )
+
+    def __init__(self):
+        self.ss_block = self.es_block = None
+        self.first_transition = True
+        self.first_samplenum = None
+        self.start_samplenum = None
+        self.end_samplenum = None
+        self.oldpin = None
+        self.num_cycles = 0
+        self.average = 0
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def start(self):
+        self.startedge = 0 if self.options['polarity'] == 'active-low' else 1
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+        self.out_average = \
+            self.register(srd.OUTPUT_META,
+                          meta=(float, 'Average', 'PWM base (cycle) frequency'))
+
+    def putx(self, data):
+        self.put(self.ss_block, self.es_block, self.out_ann, data)
+
+    def putp(self, period_t):
+        # Adjust granularity.
+        if period_t == 0 or period_t >= 1:
+            period_s = '%.1f s' % (period_t)
+        elif period_t <= 1e-12:
+            period_s = '%.1f fs' % (period_t * 1e15)
+        elif period_t <= 1e-9:
+            period_s = '%.1f ps' % (period_t * 1e12)
+        elif period_t <= 1e-6:
+            period_s = '%.1f ns' % (period_t * 1e9)
+        elif period_t <= 1e-3:
+            period_s = '%.1f μs' % (period_t * 1e6)
+        else:
+            period_s = '%.1f ms' % (period_t * 1e3)
+
+        self.put(self.ss_block, self.es_block, self.out_ann, [1, [period_s]])
+
+    def putb(self, data):
+        self.put(self.num_cycles, self.num_cycles, self.out_binary, data)
+
+    def decode(self, ss, es, data):
+
+        for (self.samplenum, pins) in data:
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpin == pins[0]:
+                continue
+
+            # Initialize self.oldpins with the first sample value.
+            if self.oldpin is None:
+                self.oldpin = pins[0]
+                continue
+
+            if self.first_transition:
+                # First rising edge
+                if self.oldpin != self.startedge:
+                    self.first_samplenum = self.samplenum
+                    self.start_samplenum = self.samplenum
+                    self.first_transition = False
+            else:
+                if self.oldpin != self.startedge:
+                    # Rising edge
+                    # We are on a full cycle we can calculate
+                    # the period, the duty cycle and its ratio.
+                    period = self.samplenum - self.start_samplenum
+                    duty = self.end_samplenum - self.start_samplenum
+                    ratio = float(duty / period)
+
+                    # This interval starts at this edge.
+                    self.ss_block = self.start_samplenum
+                    # Store the new rising edge position and the ending
+                    # edge interval.
+                    self.start_samplenum = self.es_block = self.samplenum
+
+                    # Report the duty cycle in percent.
+                    percent = float(ratio * 100)
+                    self.putx([0, ['%f%%' % percent]])
+
+                    # Report the duty cycle in the binary output.
+                    self.putb([0, bytes([int(ratio * 256)])])
+
+                    # Report the period in units of time.
+                    period_t = float(period / self.samplerate)
+                    self.putp(period_t)
+
+                    # Update and report the new duty cycle average.
+                    self.num_cycles += 1
+                    self.average += percent
+                    self.put(self.first_samplenum, self.es_block, self.out_average,
+                             float(self.average / self.num_cycles))
+                else:
+                    # Falling edge
+                    self.end_samplenum = self.ss_block = self.samplenum
+
+            self.oldpin = pins[0]
diff --git a/decoders/ir_nec/__init__.py b/decoders/qi/__init__.py
similarity index 79%
copy from decoders/ir_nec/__init__.py
copy to decoders/qi/__init__.py
index 84bf428..35ffe5b 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/qi/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Josef Gajdusek <atx at atx.name>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder decodes demodulated data streams used by the Qi standard
+for communication from the receiver to the charging station.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/qi/pd.py b/decoders/qi/pd.py
new file mode 100644
index 0000000..6db4bf5
--- /dev/null
+++ b/decoders/qi/pd.py
@@ -0,0 +1,244 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Josef Gajdusek <atx at atx.name>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import operator
+import collections
+from functools import reduce
+
+end_codes = (
+    'Unknown',
+    'Charge Complete',
+    'Internal Fault',
+    'Over Temperature',
+    'Over Voltage',
+    'Over Current',
+    'Battery Failure',
+    'Reconfigure',
+    'No Response',
+)
+
+class SamplerateError(Exception):
+    pass
+
+def calc_checksum(packet):
+    return reduce(operator.xor, packet[:-1])
+
+def bits_to_uint(bits):
+    # LSB first
+    return reduce(lambda i, v: (i >> 1) | (v << (len(bits) - 1)), bits, 0)
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'qi'
+    name = 'Qi'
+    longname = 'Qi charger protocol'
+    desc = 'Protocol used by Qi receiver'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['qi']
+    channels = (
+        {'id': 'qi', 'name': 'Qi', 'desc': 'Demodulated Qi data line'},
+    )
+    annotations = (
+        ('bits', 'Bits'),
+        ('bytes-errors', 'Bit errors'),
+        ('bytes-start', 'Start bits'),
+        ('bytes-info', 'Info bits'),
+        ('bytes-data', 'Data bytes'),
+        ('packets-data', 'Packet data'),
+        ('packets-checksum-ok', 'Packet checksum'),
+        ('packets-checksum-err', 'Packet checksum'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0,)),
+        ('bytes', 'Bytes', (1, 2, 3, 4)),
+        ('packets', 'Packets', (5, 6, 7)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.reset_variables()
+
+    def reset_variables(self):
+        self.counter = 0
+        self.prev = None
+        self.state = 'IDLE'
+        self.lastbit = 0
+        self.bytestart = 0
+        self.deq = collections.deque(maxlen = 2)
+        self.bits = []
+        self.bitsi = [0]
+        self.bytesi = []
+        self.packet = []
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+            self.bit_width = float(self.samplerate) / 2e3
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.reset_variables()
+
+    def packet_len(self, byte):
+        if 0x00 <= byte <= 0x1f:
+            return int(1 + (byte - 0) / 32)
+        if 0x20 <= byte <= 0x7f:
+            return int(2 + (byte - 32) / 16)
+        if 0x80 <= byte <= 0xdf:
+            return int(8 + (byte - 128) / 8)
+        if 0xe0 <= byte <= 0xff:
+            return int(20 + (byte - 224) / 4)
+
+    def in_tolerance(self, l):
+        return (0.75 * self.bit_width) < l < (1.25 * self.bit_width)
+
+    def putp(self, data):
+        self.put(self.bytesi[0], self.bytesi[-1], self.out_ann, [5, data])
+
+    def process_packet(self):
+        if self.packet[0] == 0x01: # Signal Strength
+            self.putp(['Signal Strength: %d' % self.packet[1],
+                       'SS: %d' % self.packet[1], 'SS'])
+        elif self.packet[0] == 0x02: # End Power Transfer
+            reason = end_codes[self.packet[1]] if self.packet[1] < len(end_codes) else 'Reserved'
+            self.putp(['End Power Transfer: %s' % reason,
+                       'EPT: %s' % reason, 'EPT'])
+        elif self.packet[0] == 0x03: # Control Error
+            val = self.packet[1] if self.packet[1] < 128 else (self.packet[1] & 0x7f) - 128
+            self.putp(['Control Error: %d' % val, 'CE: %d' % val, 'CE'])
+        elif self.packet[0] == 0x04: # Received Power
+            self.putp(['Received Power: %d' % self.packet[1],
+                       'RP: %d' % self.packet[1], 'RP'])
+        elif self.packet[0] == 0x05: # Charge Status
+            self.putp(['Charge Status: %d' % self.packet[1],
+                       'CS: %d' % self.packet[1], 'CS'])
+        elif self.packet[0] == 0x06: # Power Control Hold-off
+            self.putp(['Power Control Hold-off: %dms' % self.packet[1],
+                       'PCH: %d' % self.packet[1]], 'PCH')
+        elif self.packet[0] == 0x51: # Configuration
+            powerclass = (self.packet[1] & 0xc0) >> 7
+            maxpower = self.packet[1] & 0x3f
+            prop = (self.packet[3] & 0x80) >> 7
+            count = self.packet[3] & 0x07
+            winsize = (self.packet[4] & 0xf8) >> 3
+            winoff = self.packet[4] & 0x07
+            self.putp(['Configuration: Power Class = %d, Maximum Power = %d, Prop = %d,'
+                       'Count = %d, Window Size = %d, Window Offset = %d' %
+                       (powerclass, maxpower, prop, count, winsize, winoff),
+                       'C: PC = %d MP = %d P = %d C = %d WS = %d WO = %d' %
+                       (powerclass, maxpower, prop, count, winsize, winoff),
+                       'Configuration', 'C'])
+        elif self.packet[0] == 0x71: # Identification 
+            version = '%d.%d' % ((self.packet[1] & 0xf0) >> 4, self.packet[1] & 0x0f)
+            mancode = '%02x%02x' % (self.packet[2], self.packet[3])
+            devid = '%02x%02x%02x%02x' % (self.packet[4] & ~0x80,
+                    self.packet[5], self.packet[6], self.packet[7])
+            self.putp(['Identification: Version = %s, Manufacturer = %s, ' \
+                       'Device = %s' % (version, mancode, devid),
+                       'ID: %s %s %s' % (version, mancode, devid), 'ID'])
+        elif self.packet[0] == 0x81: # Extended Identification
+            edevid = '%02x%02x%02x%02x%02x%02x%02x%02x' % self.packet[1:-1]
+            self.putp(['Extended Identification: %s' % edevid,
+                       'EI: %s' % edevid, 'EI'])
+        elif self.packet[0] in (0x18, 0x19, 0x28, 0x29, 0x38, 0x48, 0x58, 0x68,
+                0x78, 0x85, 0xa4, 0xc4, 0xe2): # Proprietary
+            self.putp(['Proprietary', 'P'])
+        else: # Unknown
+            self.putp(['Unknown', '?'])
+        self.put(self.bytesi[-1], self.samplenum, self.out_ann,
+                 [6, ['Checksum OK', 'OK']] if \
+                 calc_checksum(self.packet) == self.packet[-1]
+                 else [6, ['Checksum error', 'ERR']])
+
+    def process_byte(self):
+        self.put(self.bytestart, self.bitsi[0], self.out_ann,
+                 ([2, ['Start bit', 'Start', 'S']]) if self.bits[0] == 0 else
+                 ([1, ['Start error', 'Start err', 'SE']]))
+        databits = self.bits[1:9]
+        data = bits_to_uint(databits)
+        parity = reduce(lambda i, v: (i + v) % 2, databits, 1)
+        self.put(self.bitsi[0], self.bitsi[8], self.out_ann, [4, ['%02x' % data]])
+        self.put(self.bitsi[8], self.bitsi[9], self.out_ann,
+                 ([3, ['Parity bit', 'Parity', 'P']]) if self.bits[9] == parity else
+                 ([1, ['Parity error', 'Parity err', 'PE']]))
+        self.put(self.bitsi[9], self.bitsi[10], self.out_ann,
+                 ([3, ['Stop bit', 'Stop', 'S']]) if self.bits[10] == 1 else
+                 ([1, ['Stop error', 'Stop err', 'SE']]))
+
+        self.bytesi.append(self.bytestart)
+        self.packet.append(data)
+        if self.packet_len(self.packet[0]) + 2 == len(self.packet):
+            self.process_packet()
+            self.bytesi.clear()
+            self.packet.clear()
+
+    def add_bit(self, bit):
+        self.bits.append(bit)
+        self.bitsi.append(self.samplenum)
+
+        if self.state == 'IDLE' and len(self.bits) >= 5 and \
+                                    self.bits[-5:] == [1, 1, 1, 1, 0]:
+            self.state = 'DATA'
+            self.bytestart = self.bitsi[-2]
+            self.bits = [0]
+            self.bitsi = [self.samplenum]
+            self.packet.clear()
+        elif self.state == 'DATA' and len(self.bits) == 11:
+            self.process_byte()
+            self.bytestart = self.samplenum
+            self.bits.clear()
+            self.bitsi.clear()
+        if self.state != 'IDLE':
+            self.put(self.lastbit, self.samplenum, self.out_ann, [0, ['%d' % bit]])
+        self.lastbit = self.samplenum
+
+    def handle_transition(self, l, htl):
+        self.deq.append(l)
+        if len(self.deq) >= 2 and \
+                (self.in_tolerance(self.deq[-1] + self.deq[-2]) or \
+                htl and self.in_tolerance(l * 2) and \
+                self.deq[-2] > 1.25 * self.bit_width):
+            self.add_bit(1)
+            self.deq.clear()
+        elif self.in_tolerance(l):
+            self.add_bit(0)
+            self.deq.clear()
+        elif l > (1.25 * self.bit_width):
+            self.state = 'IDLE'
+            self.bytesi.clear()
+            self.packet.clear()
+            self.bits.clear()
+            self.bitsi.clear()
+
+    def next_sample(self, s):
+        if s == self.prev:
+            self.counter += 1
+        else:
+            self.handle_transition(self.counter, s == 0)
+            self.prev = s
+            self.counter = 1
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, (qi,)) in data:
+            self.next_sample(qi)
diff --git a/decoders/ir_nec/__init__.py b/decoders/rfm12/__init__.py
similarity index 80%
copy from decoders/ir_nec/__init__.py
copy to decoders/rfm12/__init__.py
index 84bf428..725d443 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/rfm12/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2014 Sławek Piotrowski <sentinel at atteo.org>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'spi' PD and decodes the HopeRF RFM12
+wireless transceiver control protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/rfm12/pd.py b/decoders/rfm12/pd.py
new file mode 100644
index 0000000..46e5b07
--- /dev/null
+++ b/decoders/rfm12/pd.py
@@ -0,0 +1,494 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Sławek Piotrowski <sentinel at atteo.org>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'rfm12'
+    name = 'RFM12'
+    longname = 'RFM12 control protocol'
+    desc = 'HopeRF RFM12 wireless transceiver control protocol.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['rfm12']
+    annotations = (
+        ('cmd', 'Command'),
+        ('params', 'Command parameters'),
+        ('disabled', 'Disabled bits'),
+        ('return', 'Returned values'),
+        ('disabled_return', 'Disabled returned values'),
+        ('interpretation', 'Interpretation'),
+    )
+    annotation_rows = (
+        ('commands', 'Commands', (0, 1, 2)),
+        ('return', 'Return', (3, 4)),
+        ('interpretation', 'Interpretation', (5,)),
+    )
+
+    def __init__(self):
+        self.mosi_bytes, self.miso_bytes = [], []
+        self.mosi_bits, self.miso_bits = [], []
+        self.row_pos = [0, 0, 0]
+
+        self.ann_to_row = [0, 0, 0, 1, 1, 2]
+
+        # Initialize with Power-On-Reset values.
+        self.last_status = [0x00, 0x00]
+        self.last_config = 0x08
+        self.last_power = 0x08
+        self.last_freq = 0x680
+        self.last_data_rate = 0x23
+        self.last_fifo_and_reset = 0x80
+        self.last_afc = 0xF7
+        self.last_transceiver = 0x00
+        self.last_pll = 0x77
+
+    def advance_ann(self, ann, length):
+        row = self.ann_to_row[ann]
+        self.row_pos[row] += length
+
+    def putx(self, ann, length, description):
+        if not isinstance(description, list):
+            description = [description]
+        row = self.ann_to_row[ann]
+        bit = self.row_pos[row]
+        self.put(self.mosi_bits[bit][1], self.mosi_bits[bit + length - 1][2],
+                 self.out_ann, [ann, description])
+        bit += length
+        self.row_pos[row] = bit
+
+    def describe_bits(self, data, names):
+        i = 0x01 << len(names) - 1
+        bit = 0
+        while i != 0:
+            if names[bit] != '':
+                self.putx(1 if (data & i) else 2, 1, names[bit])
+            i >>= 1
+            bit += 1
+
+    def describe_return_bits(self, data, names):
+        i = 0x01 << len(names) - 1
+        bit = 0
+        while i != 0:
+            if names[bit] != '':
+                self.putx(3 if (data & i) else 4, 1, names[bit])
+            else:
+                self.advance_ann(3, 1)
+            i >>= 1
+            bit += 1
+
+    def describe_changed_bits(self, data, old_data, names):
+        changes = data ^ old_data
+        i = 0x01 << (len(names) - 1)
+        bit = 0
+        while i != 0:
+            if names[bit] != '' and changes & i:
+                s = ['+', 'Turning on'] if (data & i) else ['-', 'Turning off']
+                self.putx(5, 1, s)
+            else:
+                self.advance_ann(5, 1)
+            i >>= 1
+            bit += 1
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def handle_configuration_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Configuration command', 'Configuration'])
+        NAMES = [['Internal data register', 'el'], ['FIFO mode', 'ef']]
+
+        bits = (cmd[1] & 0xC0) >> 6
+        old_bits = (self.last_config & 0xC0) >> 6
+        self.describe_bits(bits, NAMES)
+        self.describe_changed_bits(bits, old_bits, NAMES)
+
+        FREQUENCIES = ['315', '433', '868', '915']
+        f = FREQUENCIES[(cmd[1] & 0x30) >> 4] + 'MHz'
+        self.putx(1, 2, ['Frequency: ' + f, f])
+        if cmd[1] & 0x30 != self.last_config & 0x30:
+            self.putx(5, 2, ['Changed', '~'])
+
+        c = '%.1fpF' % (8.5 + (cmd[1] & 0xF) * 0.5)
+        self.putx(1, 4, ['Capacitance: ' + c, c])
+        if cmd[1] & 0xF != self.last_config & 0xF:
+            self.putx(5, 4, ['Changed', '~'])
+
+        self.last_config = cmd[1]
+
+    def handle_power_management_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Power management', 'Power'])
+        NAMES = [['Receiver chain', 'er'], ['Baseband circuit', 'ebb'],
+                 ['Transmission', 'et'], ['Synthesizer', 'es'],
+                 ['Crystal oscillator', 'ex'], ['Low battery detector', 'eb'],
+                 ['Wake-up timer', 'ew'], ['Clock output off switch', 'dc']]
+
+        self.describe_bits(cmd[1], NAMES)
+
+        power = cmd[1]
+
+        # Some bits imply other, even if they are set to 0.
+        if power & 0x80:
+            power |= 0x58
+        if power & 0x20:
+            power |= 0x18
+        self.describe_changed_bits(power, self.last_power, NAMES)
+
+        self.last_power = power
+
+    def handle_frequency_setting_cmd(self, cmd, ret):
+        self.putx(0, 4, ['Frequency setting', 'Frequency'])
+        f = ((cmd[1] & 0xF) << 8) + cmd[2]
+        self.putx(0, 12, ['F = %3.4f' % f])
+        self.row_pos[2] -= 4
+        if self.last_freq != f:
+            self.putx(5, 12, ['Changing', '~'])
+        self.last_freq = f
+
+    def handle_data_rate_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Data rate command', 'Data rate'])
+        r = cmd[1] & 0x7F
+        cs = (cmd[1] & 0x80) >> 7
+        rate = 10000 / 29.0 / (r + 1) / (1 + 7 * cs)
+        self.putx(0, 8, ['%3.1fkbps' % rate])
+        if self.last_data_rate != cmd[1]:
+            self.putx(5, 8, ['Changing', '~'])
+        self.last_data_rate = cmd[1]
+
+    def handle_receiver_control_cmd(self, cmd, ret):
+        self.putx(0, 5, ['Receiver control command'])
+        s = 'interrupt input' if (cmd[0] & 0x04) else 'VDI output'
+        self.putx(0, 1, ['pin16 = ' + s])
+        VDI_NAMES = ['Fast', 'Medium', 'Slow', 'Always on']
+        vdi_speed = VDI_NAMES[cmd[0] & 0x3]
+        self.putx(0, 2, ['VDI: %s' % vdi_speed])
+        BANDWIDTH_NAMES = ['Reserved', '400kHz', '340kHz', '270kHz', '200kHz',
+                           '134kHz', '67kHz', 'Reserved']
+        bandwidth = BANDWIDTH_NAMES[(cmd[1] & 0xE0) >> 5]
+        self.putx(0, 3, ['Bandwidth: %s' % bandwidth])
+        LNA_GAIN_NAMES = [0, -6, -14, -20]
+        lna_gain = LNA_GAIN_NAMES[(cmd[1] & 0x18) >> 3]
+        self.putx(0, 2, ['LNA gain: %ddB' % lna_gain])
+        RSSI_THRESHOLD_NAMES = ['-103', '-97', '-91', '-85', '-79', '-73',
+                                'Reserved', 'Reserved']
+        rssi_threshold = RSSI_THRESHOLD_NAMES[cmd[1] & 0x7]
+        self.putx(0, 3, ['RSSI threshold: %s' % rssi_threshold])
+
+    def handle_data_filter_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Data filter command'])
+        if cmd[1] & 0x80:
+            clock_recovery = 'auto'
+        elif cmd[1] & 0x40:
+            clock_recovery = 'fast'
+        else:
+            clock_recovery = 'slow'
+        self.putx(0, 2, ['Clock recovery: %s mode' % clock_recovery])
+        self.advance_ann(0, 1) # Should always be 1.
+        s = 'analog' if (cmd[1] & 0x10) else 'digital'
+        self.putx(0, 1, ['Data filter: ' + s])
+        self.advance_ann(0, 1) # Should always be 1.
+        self.putx(0, 3, ['DQD threshold: %d' % (cmd[1] & 0x7)])
+
+    def handle_fifo_and_reset_cmd(self, cmd, ret):
+        self.putx(0, 8, ['FIFO and reset command'])
+        fifo_level = (cmd[1] & 0xF0) >> 4
+        self.putx(0, 4, ['FIFO trigger level: %d' % fifo_level])
+        last_fifo_level = (self.last_fifo_and_reset & 0xF0) >> 4
+        if fifo_level != last_fifo_level:
+            self.putx(5, 4, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 4)
+        s = 'one byte' if (cmd[1] & 0x08) else 'two bytes'
+        self.putx(0, 1, ['Synchron length: ' + s])
+        if (cmd[1] & 0x08) != (self.last_fifo_and_reset & 0x08):
+            self.putx(5, 1, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 1)
+
+        if cmd[1] & 0x04:
+            fifo_fill = 'Always'
+        elif cmd[1] & 0x02:
+            fifo_fill = 'After synchron pattern'
+        else:
+            fifo_fill = 'Never'
+        self.putx(0, 2, ['FIFO fill: %s' % fifo_fill])
+        if (cmd[1] & 0x06) != (self.last_fifo_and_reset & 0x06):
+            self.putx(5, 2, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 2)
+
+        s = 'non-sensitive' if (cmd[1] & 0x01) else 'sensitive'
+        self.putx(0, 1, ['Reset mode: ' + s])
+        if (cmd[1] & 0x01) != (self.last_fifo_and_reset & 0x01):
+            self.putx(5, 1, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 1)
+
+        self.last_fifo_and_reset = cmd[1]
+
+    def handle_synchron_pattern_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Synchron pattern command'])
+        if self.last_fifo_and_reset & 0x08:
+            self.putx(0, 8, ['Pattern: 0x2D%02X' % pattern])
+        else:
+            self.putx(0, 8, ['Pattern: %02X' % pattern])
+
+    def handle_fifo_read_cmd(self, cmd, ret):
+        self.putx(0, 8, ['FIFO read command', 'FIFO read'])
+        self.putx(3, 8, ['Data: %02X' % ret[1]])
+
+    def handle_afc_cmd(self, cmd, ret):
+        self.putx(0, 8, ['AFC command'])
+        MODES = ['Off', 'Once', 'During receiving', 'Always']
+        mode = (cmd[1] & 0xC0) >> 6
+        self.putx(0, 2, ['Mode: %s' % MODES[mode]])
+        if (cmd[1] & 0xC0) != (self.last_afc & 0xC0):
+            self.putx(5, 2, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 2)
+
+        range_limit = (cmd[1] & 0x30) >> 4
+        FREQ_TABLE = [0.0, 2.5, 5.0, 7.5]
+        freq_delta = FREQ_TABLE[(self.last_config & 0x30) >> 4]
+
+        if range_limit == 0:
+            self.putx(0, 2, ['Range: No limit'])
+        elif range_limit == 1:
+            self.putx(0, 2, ['Range: +/-%dkHz' % (15 * freq_delta)])
+        elif range_limit == 2:
+            self.putx(0, 2, ['Range: +/-%dkHz' % (7 * freq_delta)])
+        elif range_limit == 3:
+            self.putx(0, 2, ['Range: +/-%dkHz' % (3 * freq_delta)])
+
+        if (cmd[1] & 0x30) != (self.last_afc & 0x30):
+            self.putx(5, 2, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 2)
+
+        NAMES = ['Strobe edge', 'High accuracy mode', 'Enable offset register',
+                 'Enable offset calculation']
+        self.describe_bits(cmd[1] & 0xF, NAMES)
+        self.describe_changed_bits(cmd[1] & 0xF, self.last_afc & 0xF, NAMES)
+
+        self.last_afc = cmd[1]
+
+    def handle_transceiver_control_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Transceiver control command'])
+        self.putx(0, 4, ['FSK frequency delta: %dkHz' % (15 * ((cmd[1] & 0xF0) >> 4))])
+        if cmd[1] & 0xF0 != self.last_transceiver & 0xF0:
+            self.putx(5, 4, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 4)
+
+        POWERS = [0, -2.5, -5, -7.5, -10, -12.5, -15, -17.5]
+        self.advance_ann(0, 1)
+        self.advance_ann(5, 1)
+        self.putx(0,3, ['Relative power: %dB' % (cmd[1] & 0x07)])
+        if (cmd[1] & 0x07) != (self.last_transceiver & 0x07):
+            self.putx(5, 3, ['Changing', '~'])
+        else:
+            self.advance_ann(5, 3)
+        self.last_transceiver = cmd[1]
+
+    def handle_pll_setting_cmd(self, cmd, ret):
+        self.putx(0, 8, ['PLL setting command'])
+        self.advance_ann(0, 1)
+        self.putx(0, 2, ['Clock buffer rise and fall time'])
+        self.advance_ann(0, 1)
+        self.advance_ann(5, 4)
+        NAMES = [['Delay in phase detector', 'dly'], ['Disable dithering', 'ddit']]
+        self.describe_bits((cmd[1] & 0xC) >> 2, NAMES)
+        self.describe_changed_bits((cmd[1] & 0xC) >> 2, (self.last_pll & 0xC) >> 2, NAMES)
+        s = '256kbps, high' if (cmd[1] & 0x01) else '86.2kbps, low'
+        self.putx(0, 1, ['Max bit rate: %s noise' % s])
+
+        self.advance_ann(5, 1)
+        if (cmd[1] & 0x01) != (self.last_pll & 0x01):
+            self.putx(5, 1, ['Changing', '~'])
+
+        self.last_pll = cmd[1]
+
+    def handle_transmitter_register_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Transmitter register command', 'Transmit'])
+        self.putx(0, 8, ['Data: %s' % cmd[1], '%s' % cmd[1]])
+
+    def handle_software_reset_cmd(self, cmd, ret):
+        self.putx(0, 16, ['Software reset command'])
+
+    def handle_wake_up_timer_cmd(self, cmd, ret):
+        self.putx(0, 3, ['Wake-up timer command', 'Timer'])
+        r = cmd[0] & 0x1F
+        m = cmd[1]
+        time = 1.03 * m * pow(2, r) + 0.5
+        self.putx(0, 13, ['Time: %7.2f' % time])
+
+    def handle_low_duty_cycle_cmd(self, cmd, ret):
+        self.putx(0, 16, ['Low duty cycle command'])
+
+    def handle_low_battery_detector_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Low battery detector command'])
+        NAMES = ['1', '1.25', '1.66', '2', '2.5', '3.33', '5', '10']
+        clock = NAMES[(cmd[1] & 0xE0) >> 5]
+        self.putx(0, 3, ['Clock output: %sMHz' % clock, '%sMHz' % clock])
+        self.advance_ann(0, 1)
+        v = 2.25 + (cmd[1] & 0x0F) * 0.1
+        self.putx(0, 4, ['Low battery voltage: %1.2fV' % v, '%1.2fV' % v])
+
+    def handle_status_read_cmd(self, cmd, ret):
+        self.putx(0, 8, ['Status read command', 'Status'])
+        NAMES = ['RGIT/FFIT', 'POR', 'RGUR/FFOV', 'WKUP', 'EXT', 'LBD',
+                 'FFEM', 'RSSI/ATS', 'DQD', 'CRL', 'ATGL']
+        status = (ret[0] << 3) + (ret[1] >> 5)
+        self.row_pos[1] -= 8
+        self.row_pos[2] -= 8
+        self.describe_return_bits(status, NAMES)
+        receiver_enabled = (self.last_power & 0x80) >> 7
+
+        if ret[0] & 0x80:
+            if receiver_enabled:
+                s = 'Received data in FIFO'
+            else:
+                s = 'Transmit register ready'
+            self.putx(5, 1, s)
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x40:
+            self.putx(5, 1, 'Power on Reset')
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x20:
+            if receiver_enabled:
+                s = 'RX FIFO overflow'
+            else:
+                s = 'Transmit register under run'
+            self.putx(5, 1, s)
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x10:
+            self.putx(5, 1, 'Wake-up timer')
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x08:
+            self.putx(5, 1, 'External interrupt')
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x04:
+            self.putx(5, 1, 'Low battery')
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x02:
+            self.putx(5, 1, 'FIFO is empty')
+        else:
+            self.advance_ann(5, 1)
+        if ret[0] & 0x01:
+            if receiver_enabled:
+                s = 'Incoming signal above limit'
+            else:
+                s = 'Antenna detected RF signal'
+            self.putx(5, 1, s)
+        else:
+            self.advance_ann(5, 1)
+        if ret[1] & 0x80:
+            self.putx(5, 1, 'Data quality detector')
+        else:
+            self.advance_ann(5, 1)
+        if ret[1] & 0x40:
+            self.putx(5, 1, 'Clock recovery locked')
+        else:
+            self.advance_ann(5, 1)
+        self.advance_ann(5, 1)
+
+        self.putx(3, 5, ['AFC offset'])
+        if (self.last_status[1] & 0x1F) != (ret[1] & 0x1F):
+            self.putx(5, 5, ['Changed', '~'])
+        self.last_status = ret
+
+    def handle_cmd(self, cmd, ret):
+        if cmd[0] == 0x80:
+            self.handle_configuration_cmd(cmd, ret)
+        elif cmd[0] == 0x82:
+            self.handle_power_management_cmd(cmd, ret)
+        elif cmd[0] & 0xF0 == 0xA0:
+            self.handle_frequency_setting_cmd(cmd, ret)
+        elif cmd[0] == 0xC6:
+            self.handle_data_rate_cmd(cmd, ret)
+        elif cmd[0] & 0xF8 == 0x90:
+            self.handle_receiver_control_cmd(cmd, ret)
+        elif cmd[0] == 0xC2:
+            self.handle_data_filter_cmd(cmd, ret)
+        elif cmd[0] == 0xCA:
+            self.handle_fifo_and_reset_cmd(cmd, ret)
+        elif cmd[0] == 0xCE:
+            self.handle_synchron_pattern_cmd(cmd, ret)
+        elif cmd[0] == 0xB0:
+            self.handle_fifo_read_cmd(cmd, ret)
+        elif cmd[0] == 0xC4:
+            self.handle_afc_cmd(cmd, ret)
+        elif cmd[0] & 0xFE == 0x98:
+            self.handle_transceiver_control_cmd(cmd, ret)
+        elif cmd[0] == 0xCC:
+            self.handle_pll_setting_cmd(cmd, ret)
+        elif cmd[0] == 0xB8:
+            self.handle_transmitter_register_cmd(cmd, ret)
+        elif cmd[0] == 0xFE:
+            self.handle_software_reset_cmd(cmd, ret)
+        elif cmd[0] & 0xE0 == 0xE0:
+            self.handle_wake_up_timer_cmd(cmd, ret)
+        elif cmd[0] == 0xC8:
+            self.handle_low_duty_cycle_cmd(cmd, ret)
+        elif cmd[0] == 0xC0:
+            self.handle_low_battery_detector_cmd(cmd, ret)
+        elif cmd[0] == 0x00:
+            self.handle_status_read_cmd(cmd, ret)
+        else:
+            c = '%02x %02x' % tuple(cmd)
+            r = '%02x %02x' % tuple(ret)
+            self.putx(0, 16, ['Unknown command: %s (reply: %s)!' % (c, r)])
+
+    def decode(self, ss, es, data):
+        ptype, mosi, miso = data
+
+        # For now, only use DATA and BITS packets.
+        if ptype not in ('DATA', 'BITS'):
+            return
+
+        # Store the individual bit values and ss/es numbers. The next packet
+        # is guaranteed to be a 'DATA' packet belonging to this 'BITS' one.
+        if ptype == 'BITS':
+            if mosi is not None:
+                self.mosi_bits.extend(reversed(mosi))
+            if miso is not None:
+                self.miso_bits.extend(reversed(miso))
+            return
+
+        # Append new bytes.
+        self.mosi_bytes.append(mosi)
+        self.miso_bytes.append(miso)
+
+        # All commands consist of 2 bytes.
+        if len(self.mosi_bytes) < 2:
+            return
+
+        self.row_pos = [0, 8, 8]
+
+        self.handle_cmd(self.mosi_bytes, self.miso_bytes)
+
+        self.mosi_bytes, self.miso_bytes = [], []
+        self.mosi_bits, self.miso_bits = [], []
diff --git a/decoders/rgb_led_spi/__init__.py b/decoders/rgb_led_spi/__init__.py
index 3d41ea5..c0e0ea1 100644
--- a/decoders/rgb_led_spi/__init__.py
+++ b/decoders/rgb_led_spi/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'spi' PD and decodes generic RGB LED string
 values that are clocked over SPI in RGB values.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/rgb_led_spi/pd.py b/decoders/rgb_led_spi/pd.py
index 8577928..9a465ad 100644
--- a/decoders/rgb_led_spi/pd.py
+++ b/decoders/rgb_led_spi/pd.py
@@ -25,23 +25,23 @@ class Decoder(srd.Decoder):
     id = 'rgb_led_spi'
     name = 'RGB LED (SPI)'
     longname = 'RGB LED string decoder (SPI)'
-    desc = 'Generic RGB LED string protocol (RGB values clocked over SPI).'
-    license = 'gplv2'
+    desc = 'RGB LED string protocol (RGB values clocked over SPI).'
+    license = 'gplv2+'
     inputs = ['spi']
     outputs = ['rgb_led_spi']
     annotations = (
         ('rgb', 'RGB values'),
     )
 
-    def __init__(self, **kwargs):
-        self.cmd_ss, self.cmd_es = 0, 0
+    def __init__(self):
+        self.ss_cmd, self.es_cmd = 0, 0
         self.mosi_bytes = []
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def putx(self, data):
-        self.put(self.cmd_ss, self.cmd_es, self.out_ann, data)
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
 
     def decode(self, ss, es, data):
         ptype, mosi, miso = data
@@ -52,7 +52,7 @@ class Decoder(srd.Decoder):
         self.ss, self.es = ss, es
 
         if len(self.mosi_bytes) == 0:
-            self.cmd_ss = ss
+            self.ss_cmd = ss
         self.mosi_bytes.append(mosi)
 
         # RGB value == 3 bytes
@@ -60,10 +60,8 @@ class Decoder(srd.Decoder):
             return
 
         red, green, blue = self.mosi_bytes
-        rgb_value  = int(red) << 16
-        rgb_value |= int(green) << 8
-        rgb_value |= int(blue)
+        rgb_value = int(red) << 16 | int(green) << 8 | int(blue)
 
-        self.cmd_es = es
-        self.putx([0, ["#%.6x" % rgb_value]])
+        self.es_cmd = es
+        self.putx([0, ['#%.6x' % rgb_value]])
         self.mosi_bytes = []
diff --git a/decoders/dcf77/__init__.py b/decoders/rgb_led_ws281x/__init__.py
similarity index 72%
copy from decoders/dcf77/__init__.py
copy to decoders/rgb_led_ws281x/__init__.py
index 04805c2..63135a4 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/rgb_led_ws281x/__init__.py
@@ -1,11 +1,11 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Vladimir Ermakov <vooon341 at gmail.com>
 ##
 ## 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
+## the Free Software Foundation; either version 3 of the License, or
 ## (at your option) any later version.
 ##
 ## This program is distributed in the hope that it will be useful,
@@ -19,12 +19,10 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+WS281x RGB LED protocol decoder.
 
 Details:
-http://en.wikipedia.org/wiki/DCF77
+https://cpldcpu.wordpress.com/2014/01/14/light_ws2812-library-v2-0-part-i-understanding-the-ws2812/
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/rgb_led_ws281x/pd.py b/decoders/rgb_led_ws281x/pd.py
new file mode 100644
index 0000000..6f65960
--- /dev/null
+++ b/decoders/rgb_led_ws281x/pd.py
@@ -0,0 +1,128 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Vladimir Ermakov <vooon341 at gmail.com>
+##
+## 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 3 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from functools import reduce
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'rgb_led_ws281x'
+    name = 'RGB LED (WS281x)'
+    longname = 'RGB LED string decoder (WS281x)'
+    desc = 'RGB LED string protocol (WS281x).'
+    license = 'gplv3+'
+    inputs = ['logic']
+    outputs = ['rgb_led_ws281x']
+    channels = (
+        {'id': 'din', 'name': 'DIN', 'desc': 'DIN data line'},
+    )
+    annotations = (
+        ('bit', 'Bit'),
+        ('reset', 'RESET'),
+        ('rgb', 'RGB'),
+    )
+    annotation_rows = (
+        ('bit', 'Bits', (0, 1)),
+        ('rgb', 'RGB', (2,)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.oldpin = None
+        self.ss_packet = None
+        self.ss = None
+        self.es = None
+        self.bits = []
+        self.inreset = False
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def handle_bits(self, samplenum):
+        if len(self.bits) == 24:
+            grb = reduce(lambda a, b: (a << 1) | b, self.bits)
+            rgb = (grb & 0xff0000) >> 8 | (grb & 0x00ff00) << 8 | (grb & 0x0000ff)
+            self.put(self.ss_packet, samplenum, self.out_ann,
+                     [2, ['#%06x' % rgb]])
+            self.bits = []
+            self.ss_packet = None
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+
+        for (samplenum, (pin, )) in data:
+            if self.oldpin is None:
+                self.oldpin = pin
+                continue
+
+            # Check RESET condition (manufacturer recommends 50 usec minimal,
+            # but real minimum is ~10 usec).
+            if not self.inreset and not pin and self.es is not None and \
+                    (samplenum - self.es) / self.samplerate > 50e-6:
+
+                # Decode last bit value.
+                tH = (self.es - self.ss) / self.samplerate
+                bit_ = True if tH >= 625e-9 else False
+
+                self.bits.append(bit_)
+                self.handle_bits(self.es)
+
+                self.put(self.ss, self.es, self.out_ann, [0, ['%d' % bit_]])
+                self.put(self.es, samplenum, self.out_ann,
+                         [1, ['RESET', 'RST', 'R']])
+
+                self.inreset = True
+                self.bits = []
+                self.ss_packet = None
+                self.ss = None
+
+            if not self.oldpin and pin:
+                # Rising edge.
+                if self.ss and self.es:
+                    period = samplenum - self.ss
+                    duty = self.es - self.ss
+                    # Ideal duty for T0H: 33%, T1H: 66%.
+                    bit_ = (duty / period) > 0.5
+
+                    self.put(self.ss, samplenum, self.out_ann,
+                             [0, ['%d' % bit_]])
+
+                    self.bits.append(bit_)
+                    self.handle_bits(samplenum)
+
+                if self.ss_packet is None:
+                    self.ss_packet = samplenum
+
+                self.ss = samplenum
+
+            elif self.oldpin and not pin:
+                # Falling edge.
+                self.inreset = False
+                self.es = samplenum
+
+            self.oldpin = pin
diff --git a/decoders/rtc8564/__init__.py b/decoders/rtc8564/__init__.py
index 9a397b1..e2776a6 100644
--- a/decoders/rtc8564/__init__.py
+++ b/decoders/rtc8564/__init__.py
@@ -23,5 +23,4 @@ This decoder stacks on top of the 'i2c' PD and decodes the Epson
 RTC-8564 JE/NB real-time clock (RTC) protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/rtc8564/pd.py b/decoders/rtc8564/pd.py
index f13af36..4ecc15a 100644
--- a/decoders/rtc8564/pd.py
+++ b/decoders/rtc8564/pd.py
@@ -19,10 +19,7 @@
 ##
 
 import sigrokdecode as srd
-
-# Return the specified BCD number (max. 8 bits) as integer.
-def bcd2int(b):
-    return (b & 0x0f) + ((b >> 4) * 10)
+from common.srdhelper import bcd2int
 
 def reg_list():
     l = []
@@ -55,7 +52,7 @@ class Decoder(srd.Decoder):
         ('date-time', 'Date/time', (9, 10)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
         self.hours = -1
         self.minutes = -1
@@ -189,7 +186,7 @@ class Decoder(srd.Decoder):
             if cmd != 'START':
                 return
             self.state = 'GET SLAVE ADDR'
-            self.block_start_sample = ss
+            self.ss_block = ss
         elif self.state == 'GET SLAVE ADDR':
             # Wait for an address write operation.
             # TODO: We should only handle packets to the RTC slave (0xa2/0xa3).
@@ -220,7 +217,7 @@ class Decoder(srd.Decoder):
                 # TODO: Handle read/write of only parts of these items.
                 d = '%02d.%02d.%02d %02d:%02d:%02d' % (self.days, self.months,
                     self.years, self.hours, self.minutes, self.seconds)
-                self.put(self.block_start_sample, es, self.out_ann,
+                self.put(self.ss_block, es, self.out_ann,
                          [9, ['Write date/time: %s' % d, 'Write: %s' % d,
                               'W: %s' % d]])
                 self.state = 'IDLE'
@@ -246,12 +243,9 @@ class Decoder(srd.Decoder):
             elif cmd == 'STOP':
                 d = '%02d.%02d.%02d %02d:%02d:%02d' % (self.days, self.months,
                     self.years, self.hours, self.minutes, self.seconds)
-                self.put(self.block_start_sample, es, self.out_ann,
+                self.put(self.ss_block, es, self.out_ann,
                          [10, ['Read date/time: %s' % d, 'Read: %s' % d,
                                'R: %s' % d]])
                 self.state = 'IDLE'
             else:
                 pass # TODO?
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/tlc5620/__init__.py b/decoders/sdcard_sd/__init__.py
similarity index 86%
copy from decoders/tlc5620/__init__.py
copy to decoders/sdcard_sd/__init__.py
index c615760..c43f623 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/sdcard_sd/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Uwe Hermann <uwe at hermann-uwe.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
@@ -19,8 +19,7 @@
 ##
 
 '''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
+SD card (SD mode) low-level protocol decoder.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/sdcard_sd/lists.py b/decoders/sdcard_sd/lists.py
new file mode 100644
index 0000000..479c9f3
--- /dev/null
+++ b/decoders/sdcard_sd/lists.py
@@ -0,0 +1,185 @@
+##
+## This file is part of the sigrok project.
+##
+## Copyright (C) 2015 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+# Normal commands (CMD)
+# Unlisted items are 'Reserved' as per SD spec. The 'Unknown' items don't
+# seem to be mentioned in the spec, but aren't marked as reserved either.
+cmd_names = {
+    0:  'GO_IDLE_STATE',
+    # 1: Reserved
+    2:  'ALL_SEND_CID',
+    3:  'SEND_RELATIVE_ADDR',
+    4:  'SET_DSR',
+    5:  'IO_SEND_OP_COND', # SDIO-only
+    6:  'SWITCH_FUNC', # New since spec 1.10
+    7:  'SELECT/DESELECT_CARD',
+    8:  'SEND_IF_COND',
+    9:  'SEND_CSD',
+    10: 'SEND_CID',
+    11: 'VOLTAGE_SWITCH',
+    12: 'STOP_TRANSMISSION',
+    13: 'SEND_STATUS',
+    # 14: Reserved
+    15: 'GO_INACTIVE_STATE',
+    16: 'SET_BLOCKLEN',
+    17: 'READ_SINGLE_BLOCK',
+    18: 'READ_MULTIPLE_BLOCK',
+    19: 'SEND_TUNING_BLOCK',
+    20: 'SPEED_CLASS_CONTROL',
+    # 21-22: Reserved
+    23: 'SET_BLOCK_COUNT',
+    24: 'WRITE_BLOCK',
+    25: 'WRITE_MULTIPLE_BLOCK',
+    26: 'Reserved for manufacturer',
+    27: 'PROGRAM_CSD',
+    28: 'SET_WRITE_PROT',
+    29: 'CLR_WRITE_PROT',
+    30: 'SEND_WRITE_PROT',
+    # 31: Reserved
+    32: 'ERASE_WR_BLK_START',
+    33: 'ERASE_WR_BLK_END',
+    34: 'Reserved for CMD6', # New since spec 1.10
+    35: 'Reserved for CMD6', # New since spec 1.10
+    36: 'Reserved for CMD6', # New since spec 1.10
+    37: 'Reserved for CMD6', # New since spec 1.10
+    38: 'ERASE',
+    # 39: Reserved
+    40: 'Reserved for security specification',
+    # 41: Reserved
+    42: 'LOCK_UNLOCK',
+    # 43-49: Reserved
+    50: 'Reserved for CMD6', # New since spec 1.10
+    # 51: Reserved
+    52: 'IO_RW_DIRECT', # SDIO-only
+    53: 'IO_RW_EXTENDED', # SDIO-only
+    54: 'Unknown',
+    55: 'APP_CMD',
+    56: 'GEN_CMD',
+    57: 'Reserved for CMD6', # New since spec 1.10
+    # 58-59: Reserved
+    60: 'Reserved for manufacturer',
+    61: 'Reserved for manufacturer',
+    62: 'Reserved for manufacturer',
+    63: 'Reserved for manufacturer',
+}
+
+# Application-specific commands (ACMD)
+# Unlisted items are 'Reserved' as per SD spec. The 'Unknown' items don't
+# seem to be mentioned in the spec, but aren't marked as reserved either.
+acmd_names = {
+    # 1-5: Reserved
+    6:  'SET_BUS_WIDTH',
+    # 7-12: Reserved
+    13: 'SD_STATUS',
+    14: 'Reserved for Security Application',
+    15: 'Reserved for Security Application',
+    16: 'Reserved for Security Application',
+    # 17: Reserved
+    18: 'Reserved for SD security applications',
+    # 19-21: Reserved
+    22: 'SEND_NUM_WR_BLOCKS',
+    23: 'SET_WR_BLK_ERASE_COUNT',
+    # 24: Reserved
+    25: 'Reserved for SD security applications',
+    26: 'Reserved for SD security applications',
+    27: 'Reserved for security specification',
+    28: 'Reserved for security specification',
+    # 29: Reserved
+    30: 'Reserved for security specification',
+    31: 'Reserved for security specification',
+    32: 'Reserved for security specification',
+    33: 'Reserved for security specification',
+    34: 'Reserved for security specification',
+    35: 'Reserved for security specification',
+    # 36-37: Reserved
+    38: 'Reserved for SD security applications',
+    # 39-40: Reserved
+    41: 'SD_SEND_OP_COND',
+    42: 'SET_CLR_CARD_DETECT',
+    43: 'Reserved for SD security applications',
+    44: 'Reserved for SD security applications',
+    45: 'Reserved for SD security applications',
+    46: 'Reserved for SD security applications',
+    47: 'Reserved for SD security applications',
+    48: 'Reserved for SD security applications',
+    49: 'Reserved for SD security applications',
+    50: 'Unknown',
+    51: 'SEND_SCR',
+    52: 'Reserved for security specification',
+    53: 'Reserved for security specification',
+    54: 'Reserved for security specification',
+    55: 'Non-existant', # Doesn't exist (equivalent to CMD55)
+    56: 'Reserved for security specification',
+    57: 'Reserved for security specification',
+    58: 'Reserved for security specification',
+    59: 'Reserved for security specification',
+    60: 'Unknown',
+    61: 'Unknown',
+    62: 'Unknown',
+    63: 'Unknown',
+}
+
+accepted_voltages = {
+    0b0001: '2.7-3.6V',
+    0b0010: 'reserved for low voltage range',
+    0b0100: 'reserved',
+    0b1000: 'reserved',
+    # All other values: "not defined".
+}
+
+card_status = {
+    0:  'Reserved for manufacturer test mode',
+    1:  'Reserved for manufacturer test mode',
+    2:  'Reserved for application specific commands',
+    3:  'AKE_SEQ_ERROR',
+    4:  'Reserved for SDIO card',
+    5:  'APP_CMD',
+    6:  'Unknown',
+    7:  'Unknown',
+    8:  'READY_FOR_DATA',
+    9:  'CURRENT_STATE', # CURRENT_STATE is a 4-bit value (decimal: 0..15).
+    10: 'CURRENT_STATE',
+    11: 'CURRENT_STATE',
+    12: 'CURRENT_STATE',
+    13: 'ERASE_RESET',
+    14: 'CARD_ECC_DISABLED',
+    15: 'WP_ERASE_SKIP',
+    16: 'CSD_OVERWRITE',
+    17: 'Reserved for DEFERRED_RESPONSE', # See eSD addendum
+    18: 'Reserved',
+    19: 'ERROR',
+    20: 'CC_ERROR',
+    21: 'CARD_ECC_FAILED',
+    22: 'ILLEGAL_COMMAND',
+    23: 'COM_CRC_ERROR',
+    24: 'LOCK_UNLOCK_FAILED',
+    25: 'CARD_IS_LOCKED',
+    26: 'WP_VIOLATION',
+    27: 'ERASE_PARAM',
+    28: 'ERASE_SEQ_ERROR',
+    29: 'BLOCK_LEN_ERROR',
+    30: 'ADDRESS_ERROR',
+    31: 'OUT_OF_RANGE',
+}
+
+sd_status = {
+    # 311:0: Reserved for manufacturer
+    # 391:312: Reserved
+}
diff --git a/decoders/sdcard_sd/pd.py b/decoders/sdcard_sd/pd.py
new file mode 100644
index 0000000..79c2074
--- /dev/null
+++ b/decoders/sdcard_sd/pd.py
@@ -0,0 +1,444 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from common.sdcard import (cmd_names, acmd_names, accepted_voltages, card_status, sd_status)
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'sdcard_sd'
+    name = 'SD card (SD mode)'
+    longname = 'Secure Digital card (SD mode)'
+    desc = 'Secure Digital card (SD mode) low-level protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['sdcard_sd']
+    channels = (
+        {'id': 'cmd',  'name': 'CMD',  'desc': 'Command'},
+        {'id': 'clk',  'name': 'CLK',  'desc': 'Clock'},
+    )
+    optional_channels = (
+        {'id': 'dat0', 'name': 'DAT0', 'desc': 'Data pin 0'},
+        {'id': 'dat1', 'name': 'DAT1', 'desc': 'Data pin 1'},
+        {'id': 'dat2', 'name': 'DAT2', 'desc': 'Data pin 2'},
+        {'id': 'dat3', 'name': 'DAT3', 'desc': 'Data pin 3'},
+    )
+    annotations = \
+        tuple(('cmd%d' % i, 'CMD%d' % i) for i in range(64)) + \
+        tuple(('acmd%d' % i, 'ACMD%d' % i) for i in range(64)) + ( \
+        ('bits', 'Bits'),
+        ('field-start', 'Start bit'),
+        ('field-transmission', 'Transmission bit'),
+        ('field-cmd', 'Command'),
+        ('field-arg', 'Argument'),
+        ('field-crc', 'CRC'),
+        ('field-end', 'End bit'),
+        ('decoded-bits', 'Decoded bits'),
+        ('decoded-fields', 'Decoded fields'),
+    )
+    annotation_rows = (
+        ('raw-bits', 'Raw bits', (128,)),
+        ('decoded-bits', 'Decoded bits', (135,)),
+        ('decoded-fields', 'Decoded fields', (136,)),
+        ('fields', 'Fields', tuple(range(129, 135))),
+        ('cmd', 'Commands', tuple(range(128))),
+    )
+
+    def __init__(self):
+        self.state = 'GET COMMAND TOKEN'
+        self.token = []
+        self.oldpins = None
+        self.oldclk = 0
+        self.is_acmd = False # Indicates CMD vs. ACMD
+        self.cmd = None
+        self.arg = None
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putbit(self, b, data):
+        self.put(self.token[b][0], self.token[b][1], self.out_ann, [135, data])
+
+    def putt(self, data):
+        self.put(self.token[0][0], self.token[47][1], self.out_ann, data)
+
+    def putt2(self, data):
+        self.put(self.token[47][0], self.token[0][1], self.out_ann, data)
+
+    def putf(self, s, e, data):
+        self.put(self.token[s][0], self.token[e][1], self.out_ann, data)
+
+    def puta(self, s, e, data):
+        self.put(self.token[47 - 8 - e][0], self.token[47 - 8 - s][1],
+                 self.out_ann, data)
+
+    def putc(self, cmd, desc):
+        self.putt([cmd, ['%s: %s' % (self.cmd_str, desc), self.cmd_str,
+                         self.cmd_str.split(' ')[0]]])
+
+    def putr(self, cmd, desc):
+        self.putt([cmd, ['Reply: %s' % desc]])
+
+    def putr2(self, cmd, desc):
+        self.putt2([cmd, ['Reply: %s' % desc]])
+
+    def reset(self):
+        self.cmd, self.arg = None, None
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def cmd_name(self, cmd):
+        c = acmd_names if self.is_acmd else cmd_names
+        return c.get(cmd, 'Unknown')
+
+    def get_token_bits(self, cmd, n):
+        # Get a bit, return True if we already got 'n' bits, False otherwise.
+        self.token.append([self.samplenum, self.samplenum, cmd])
+        if len(self.token) > 0:
+            self.token[len(self.token) - 2][1] = self.samplenum
+        if len(self.token) < n:
+            return False
+        self.token[n - 1][1] += self.token[n - 1][0] - self.token[n - 2][0]
+        return True
+
+    def handle_common_token_fields(self):
+        s = self.token
+
+        # Annotations for each individual bit.
+        for bit in range(len(self.token)):
+            self.putf(bit, bit, [128, ['%d' % s[bit][2]]])
+
+        # CMD[47:47]: Start bit (always 0)
+        self.putf(0, 0, [129, ['Start bit', 'Start', 'S']])
+
+        # CMD[46:46]: Transmission bit (1 == host)
+        t = 'host' if s[1][2] == 1 else 'card'
+        self.putf(1, 1, [130, ['Transmission: ' + t, 'T: ' + t, 'T']])
+
+        # CMD[45:40]: Command index (BCD; valid: 0-63)
+        self.cmd = int('0b' + ''.join([str(s[i][2]) for i in range(2, 8)]), 2)
+        c = '%s (%d)' % (self.cmd_name(self.cmd), self.cmd)
+        self.putf(2, 7, [131, ['Command: ' + c, 'Cmd: ' + c,
+                               'CMD%d' % self.cmd, 'Cmd', 'C']])
+
+        # CMD[39:08]: Argument
+        self.putf(8, 39, [132, ['Argument', 'Arg', 'A']])
+
+        # CMD[07:01]: CRC7
+        self.crc = int('0b' + ''.join([str(s[i][2]) for i in range(40, 47)]), 2)
+        self.putf(40, 46, [133, ['CRC: 0x%x' % self.crc, 'CRC', 'C']])
+
+        # CMD[00:00]: End bit (always 1)
+        self.putf(47, 47, [134, ['End bit', 'End', 'E']])
+
+    def get_command_token(self, cmd):
+        # Command tokens (48 bits) are sent serially (MSB-first) by the host
+        # (over the CMD line), either to one SD card or to multiple ones.
+        #
+        # Format:
+        #  - Bits[47:47]: Start bit (always 0)
+        #  - Bits[46:46]: Transmission bit (1 == host)
+        #  - Bits[45:40]: Command index (BCD; valid: 0-63)
+        #  - Bits[39:08]: Argument
+        #  - Bits[07:01]: CRC7
+        #  - Bits[00:00]: End bit (always 1)
+
+        if not self.get_token_bits(cmd, 48):
+            return
+
+        self.handle_common_token_fields()
+
+        # Handle command.
+        s = 'ACMD' if self.is_acmd else 'CMD'
+        self.cmd_str = '%s%d (%s)' % (s, self.cmd, self.cmd_name(self.cmd))
+        if self.cmd in (0, 2, 3, 4, 6, 7, 8, 9, 10, 13, 41, 51, 55):
+            self.state = 'HANDLE CMD%d' % self.cmd
+        else:
+            self.state = 'HANDLE CMD999'
+            self.putc(self.cmd, '%s%d' % (s, self.cmd))
+
+    def handle_cmd0(self):
+        # CMD0 (GO_IDLE_STATE) -> no response
+        self.puta(0, 31, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(0, 'Reset all SD cards')
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_cmd2(self):
+        # CMD2 (ALL_SEND_CID) -> R2
+        self.puta(0, 31, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(2, 'Ask card for CID number')
+        self.token, self.state = [], 'GET RESPONSE R2'
+
+    def handle_cmd3(self):
+        # CMD3 (SEND_RELATIVE_ADDR) -> R6
+        self.puta(0, 31, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(3, 'Ask card for new relative card address (RCA)')
+        self.token, self.state = [], 'GET RESPONSE R6'
+
+    def handle_cmd6(self):
+        # CMD6 (SWITCH_FUNC) -> R1
+        self.putc(6, 'Switch/check card function')
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_cmd7(self):
+        # CMD7 (SELECT/DESELECT_CARD) -> R1b
+        self.putc(7, 'Select / deselect card')
+        self.token, self.state = [], 'GET RESPONSE R6'
+
+    def handle_cmd8(self):
+        # CMD8 (SEND_IF_COND) -> R7
+        self.puta(12, 31, [136, ['Reserved', 'Res', 'R']])
+        self.puta(8, 11, [136, ['Supply voltage', 'Voltage', 'VHS', 'V']])
+        self.puta(0, 7, [136, ['Check pattern', 'Check pat', 'Check', 'C']])
+        self.putc(0, 'Send interface condition to card')
+        self.token, self.state = [], 'GET RESPONSE R7'
+        # TODO: Handle case when card doesn't reply with R7 (no reply at all).
+
+    def handle_cmd9(self):
+        # CMD9 (SEND_CSD) -> R2
+        self.puta(16, 31, [136, ['RCA', 'R']])
+        self.puta(0, 15, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(9, 'Send card-specific data (CSD)')
+        self.token, self.state = [], 'GET RESPONSE R2'
+
+    def handle_cmd10(self):
+        # CMD10 (SEND_CID) -> R2
+        self.puta(16, 31, [136, ['RCA', 'R']])
+        self.puta(0, 15, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(9, 'Send card identification data (CID)')
+        self.token, self.state = [], 'GET RESPONSE R2'
+
+    def handle_cmd13(self):
+        # CMD13 (SEND_STATUS) -> R1
+        self.puta(16, 31, [136, ['RCA', 'R']])
+        self.puta(0, 15, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(13, 'Send card status register')
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_cmd16(self):
+        # CMD16 (SET_BLOCKLEN) -> R1
+        self.blocklen = self.arg
+        self.puta(0, 31, [136, ['Block length', 'Blocklen', 'BL', 'B']])
+        self.putc(16, 'Set the block length to %d bytes' % self.blocklen)
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_cmd55(self):
+        # CMD55 (APP_CMD) -> R1
+        self.puta(16, 31, [136, ['RCA', 'R']])
+        self.puta(0, 15, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(55, 'Next command is an application-specific command')
+        self.is_acmd = True
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_acmd6(self):
+        # ACMD6 (SET_BUS_WIDTH) -> R1
+        self.putc(64 + 6, 'Read SD config register (SCR)')
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_acmd13(self):
+        # ACMD13 (SD_STATUS) -> R1
+        self.puta(0, 31, [136, ['Stuff bits', 'Stuff', 'SB', 'S']])
+        self.putc(64 + 13, 'Set SD status')
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_acmd41(self):
+        # ACMD41 (SD_SEND_OP_COND) -> R3
+        self.puta(0, 23, [136, ['VDD voltage window', 'VDD volt', 'VDD', 'V']])
+        self.puta(24, 24, [136, ['S18R']])
+        self.puta(25, 27, [136, ['Reserved', 'Res', 'R']])
+        self.puta(28, 28, [136, ['XPC']])
+        self.puta(29, 29, [136, ['Reserved for eSD', 'Reserved', 'Res', 'R']])
+        self.puta(30, 30, [136, ['Host capacity support info', 'Host capacity',
+                                 'HCS', 'H']])
+        self.puta(31, 31, [136, ['Reserved', 'Res', 'R']])
+        self.putc(64 + 41, 'Send HCS info and activate the card init process')
+        self.token, self.state = [], 'GET RESPONSE R3'
+
+    def handle_acmd51(self):
+        # ACMD51 (SEND_SCR) -> R1
+        self.putc(64 + 51, 'Read SD config register (SCR)')
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_cmd999(self):
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    def handle_acmd999(self):
+        self.token, self.state = [], 'GET RESPONSE R1'
+
+    # Response tokens can have one of four formats (depends on content).
+    # They can have a total length of 48 or 136 bits.
+    # They're sent serially (MSB-first) by the card that the host
+    # addressed previously, or (synchronously) by all connected cards.
+
+    def handle_response_r1(self, cmd):
+        # R1: Normal response command
+        #  - Bits[47:47]: Start bit (always 0)
+        #  - Bits[46:46]: Transmission bit (0 == card)
+        #  - Bits[45:40]: Command index (BCD; valid: 0-63)
+        #  - Bits[39:08]: Card status
+        #  - Bits[07:01]: CRC7
+        #  - Bits[00:00]: End bit (always 1)
+        if not self.get_token_bits(cmd, 48):
+            return
+        self.handle_common_token_fields()
+        self.putr(55, 'R1')
+        self.puta(0, 31, [136, ['Card status', 'Status', 'S']])
+        for i in range(32):
+            self.putbit(8 + i, [card_status[31 - i]])
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_response_r1b(self, cmd):
+        # R1b: Same as R1 with an optional busy signal (on the data line)
+        if not self.get_token_bits(cmd, 48):
+            return
+        self.handle_common_token_fields()
+        self.puta(0, 31, [136, ['Card status', 'Status', 'S']])
+        self.putr(55, 'R1b')
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_response_r2(self, cmd):
+        # R2: CID/CSD register
+        #  - Bits[135:135]: Start bit (always 0)
+        #  - Bits[134:134]: Transmission bit (0 == card)
+        #  - Bits[133:128]: Reserved (always 0b111111)
+        #  - Bits[127:001]: CID or CSD register including internal CRC7
+        #  - Bits[000:000]: End bit (always 1)
+        if not self.get_token_bits(cmd, 136):
+            return
+        # Annotations for each individual bit.
+        for bit in range(len(self.token)):
+            self.putf(bit, bit, [128, ['%d' % self.token[bit][2]]])
+        self.putf(0, 0, [129, ['Start bit', 'Start', 'S']])
+        t = 'host' if self.token[1][2] == 1 else 'card'
+        self.putf(1, 1, [130, ['Transmission: ' + t, 'T: ' + t, 'T']])
+        self.putf(2, 7, [131, ['Reserved', 'Res', 'R']])
+        self.putf(8, 134, [132, ['Argument', 'Arg', 'A']])
+        self.putf(135, 135, [134, ['End bit', 'End', 'E']])
+        self.putf(8, 134, [136, ['CID/CSD register', 'CID/CSD', 'C']])
+        self.putf(0, 135, [55, ['R2']])
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_response_r3(self, cmd):
+        # R3: OCR register
+        #  - Bits[47:47]: Start bit (always 0)
+        #  - Bits[46:46]: Transmission bit (0 == card)
+        #  - Bits[45:40]: Reserved (always 0b111111)
+        #  - Bits[39:08]: OCR register
+        #  - Bits[07:01]: Reserved (always 0b111111)
+        #  - Bits[00:00]: End bit (always 1)
+        if not self.get_token_bits(cmd, 48):
+            return
+        self.putr(55, 'R3')
+        # Annotations for each individual bit.
+        for bit in range(len(self.token)):
+            self.putf(bit, bit, [128, ['%d' % self.token[bit][2]]])
+        self.putf(0, 0, [129, ['Start bit', 'Start', 'S']])
+        t = 'host' if self.token[1][2] == 1 else 'card'
+        self.putf(1, 1, [130, ['Transmission: ' + t, 'T: ' + t, 'T']])
+        self.putf(2, 7, [131, ['Reserved', 'Res', 'R']])
+        self.putf(8, 39, [132, ['Argument', 'Arg', 'A']])
+        self.putf(40, 46, [133, ['Reserved', 'Res', 'R']])
+        self.putf(47, 47, [134, ['End bit', 'End', 'E']])
+        self.puta(0, 31, [136, ['OCR register', 'OCR reg', 'OCR', 'O']])
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_response_r6(self, cmd):
+        # R6: Published RCA response
+        #  - Bits[47:47]: Start bit (always 0)
+        #  - Bits[46:46]: Transmission bit (0 == card)
+        #  - Bits[45:40]: Command index (always 0b000011)
+        #  - Bits[39:24]: Argument[31:16]: New published RCA of the card
+        #  - Bits[23:08]: Argument[15:0]: Card status bits
+        #  - Bits[07:01]: CRC7
+        #  - Bits[00:00]: End bit (always 1)
+        if not self.get_token_bits(cmd, 48):
+            return
+        self.handle_common_token_fields()
+        self.puta(0, 15, [136, ['Card status bits', 'Status', 'S']])
+        self.puta(16, 31, [136, ['Relative card address', 'RCA', 'R']])
+        self.putr(55, 'R6')
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def handle_response_r7(self, cmd):
+        # R7: Card interface condition
+        #  - Bits[47:47]: Start bit (always 0)
+        #  - Bits[46:46]: Transmission bit (0 == card)
+        #  - Bits[45:40]: Command index (always 0b001000)
+        #  - Bits[39:20]: Reserved bits (all-zero)
+        #  - Bits[19:16]: Voltage accepted
+        #  - Bits[15:08]: Echo-back of check pattern
+        #  - Bits[07:01]: CRC7
+        #  - Bits[00:00]: End bit (always 1)
+        if not self.get_token_bits(cmd, 48):
+            return
+        self.handle_common_token_fields()
+
+        self.putr(55, 'R7')
+
+        # Arg[31:12]: Reserved bits (all-zero)
+        self.puta(12, 31, [136, ['Reserved', 'Res', 'R']])
+
+        # Arg[11:08]: Voltage accepted
+        v = ''.join(str(i[2]) for i in self.token[28:32])
+        av = accepted_voltages.get(int('0b' + v, 2), 'Unknown')
+        self.puta(8, 11, [136, ['Voltage accepted: ' + av, 'Voltage', 'Volt', 'V']])
+
+        # Arg[07:00]: Echo-back of check pattern
+        self.puta(0, 7, [136, ['Echo-back of check pattern', 'Echo', 'E']])
+
+        self.token, self.state = [], 'GET COMMAND TOKEN'
+
+    def decode(self, ss, es, data):
+        for (self.samplenum, pins) in data:
+
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpins == pins:
+                continue
+            self.oldpins, (cmd, clk, dat0, dat1, dat2, dat3) = pins, pins
+
+            # Wait for a rising CLK edge.
+            if not (self.oldclk == 0 and clk == 1):
+                self.oldclk = clk
+                continue
+            self.oldclk = clk
+
+            # State machine.
+            if self.state == 'GET COMMAND TOKEN':
+                if len(self.token) == 0:
+                    # Wait for start bit (CMD = 0).
+                    if cmd != 0:
+                        continue
+                self.get_command_token(cmd)
+            elif self.state.startswith('HANDLE CMD'):
+                # Call the respective handler method for the command.
+                a, cmdstr = 'a' if self.is_acmd else '', self.state[10:].lower()
+                handle_cmd = getattr(self, 'handle_%scmd%s' % (a, cmdstr))
+                handle_cmd()
+                # Leave ACMD mode again after the first command after CMD55.
+                if self.is_acmd and cmdstr not in ('55', '63'):
+                    self.is_acmd = False
+            elif self.state.startswith('GET RESPONSE'):
+                if len(self.token) == 0:
+                    # Wait for start bit (CMD = 0).
+                    if cmd != 0:
+                        continue
+                # Call the respective handler method for the response.
+                s = 'handle_response_%s' % self.state[13:].lower()
+                handle_response = getattr(self, s)
+                handle_response(cmd)
diff --git a/decoders/sdcard_spi/__init__.py b/decoders/sdcard_spi/__init__.py
index 293b654..7ce66bf 100644
--- a/decoders/sdcard_spi/__init__.py
+++ b/decoders/sdcard_spi/__init__.py
@@ -66,5 +66,4 @@ SPI mode properties (differences to SD mode):
  * The RCA register is not accessible in SPI mode.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/sdcard_spi/pd.py b/decoders/sdcard_spi/pd.py
index be20ee3..45490ad 100644
--- a/decoders/sdcard_spi/pd.py
+++ b/decoders/sdcard_spi/pd.py
@@ -19,57 +19,7 @@
 ##
 
 import sigrokdecode as srd
-
-# Normal commands (CMD)
-cmd_names = {
-    0:  'GO_IDLE_STATE',
-    1:  'SEND_OP_COND',
-    6:  'SWITCH_FUNC',
-    8:  'SEND_IF_COND',
-    9:  'SEND_CSD',
-    10: 'SEND_CID',
-    12: 'STOP_TRANSMISSION',
-    13: 'SEND_STATUS',
-    16: 'SET_BLOCKLEN',
-    17: 'READ_SINGLE_BLOCK',
-    18: 'READ_MULTIPLE_BLOCK',
-    24: 'WRITE_BLOCK',
-    25: 'WRITE_MULTIPLE_BLOCK',
-    27: 'PROGRAM_CSD',
-    28: 'SET_WRITE_PROT',
-    29: 'CLR_WRITE_PROT',
-    30: 'SEND_WRITE_PROT',
-    32: 'ERASE_WR_BLK_START_ADDR',
-    33: 'ERASE_WR_BLK_END_ADDR',
-    38: 'ERASE',
-    42: 'LOCK_UNLOCK',
-    55: 'APP_CMD',
-    56: 'GEN_CMD',
-    58: 'READ_OCR',
-    59: 'CRC_ON_OFF',
-    # CMD60-63: Reserved for manufacturer
-}
-
-# Application-specific commands (ACMD)
-acmd_names = {
-    13: 'SD_STATUS',
-    18: 'Reserved for SD security applications',
-    22: 'SEND_NUM_WR_BLOCKS',
-    23: 'SET_WR_BLK_ERASE_COUNT',
-    25: 'Reserved for SD security applications',
-    26: 'Reserved for SD security applications',
-    38: 'Reserved for SD security applications',
-    41: 'SD_SEND_OP_COND',
-    42: 'SET_CLR_CARD_DETECT',
-    43: 'Reserved for SD security applications',
-    44: 'Reserved for SD security applications',
-    45: 'Reserved for SD security applications',
-    46: 'Reserved for SD security applications',
-    47: 'Reserved for SD security applications',
-    48: 'Reserved for SD security applications',
-    49: 'Reserved for SD security applications',
-    51: 'SEND_SCR',
-}
+from common.sdcard import (cmd_names, acmd_names)
 
 class Decoder(srd.Decoder):
     api_version = 2
@@ -96,12 +46,11 @@ class Decoder(srd.Decoder):
         ('cmd-reply', 'Commands/replies', tuple(range(134))),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.state = 'IDLE'
-        self.samplenum = 0
         self.ss, self.es = 0, 0
-        self.bit_ss, self.bit_es = 0, 0
-        self.cmd_ss, self.cmd_es = 0, 0
+        self.ss_bit, self.es_bit = 0, 0
+        self.ss_cmd, self.es_cmd = 0, 0
         self.cmd_token = []
         self.cmd_token_bits = []
         self.is_acmd = False # Indicates CMD vs. ACMD
@@ -113,17 +62,22 @@ class Decoder(srd.Decoder):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def putx(self, data):
-        self.put(self.cmd_ss, self.cmd_es, self.out_ann, data)
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
 
     def putc(self, cmd, desc):
         self.putx([cmd, ['%s: %s' % (self.cmd_str, desc)]])
 
     def putb(self, data):
-        self.put(self.bit_ss, self.bit_es, self.out_ann, data)
+        self.put(self.ss_bit, self.es_bit, self.out_ann, data)
 
     def cmd_name(self, cmd):
         c = acmd_names if self.is_acmd else cmd_names
-        return c.get(cmd, 'Unknown')
+        s = c.get(cmd, 'Unknown')
+        # SD mode names for CMD32/33: ERASE_WR_BLK_{START,END}.
+        # SPI mode names for CMD32/33: ERASE_WR_BLK_{START,END}_ADDR.
+        if cmd in (32, 33):
+            s += '_ADDR'
+        return s
 
     def handle_command_token(self, mosi, miso):
         # Command tokens (6 bytes) are sent (MSB-first) by the host.
@@ -137,7 +91,7 @@ class Decoder(srd.Decoder):
         #  - CMD[00:00]: End bit (always 1)
 
         if len(self.cmd_token) == 0:
-            self.cmd_ss = self.ss
+            self.ss_cmd = self.ss
 
         self.cmd_token.append(mosi)
         self.cmd_token_bits.append(self.mosi_bits)
@@ -146,7 +100,7 @@ class Decoder(srd.Decoder):
         if len(self.cmd_token) < 6:
             return
 
-        self.cmd_es = self.es
+        self.es_cmd = self.es
 
         t = self.cmd_token
 
@@ -157,14 +111,14 @@ class Decoder(srd.Decoder):
             return self.cmd_token_bits[5 - byte][bit]
 
         # Bits[47:47]: Start bit (always 0)
-        bit, self.bit_ss, self.bit_es = tb(5, 7)[0], tb(5, 7)[1], tb(5, 7)[2]
+        bit, self.ss_bit, self.es_bit = tb(5, 7)[0], tb(5, 7)[1], tb(5, 7)[2]
         if bit == 0:
             self.putb([134, ['Start bit: %d' % bit]])
         else:
             self.putb([135, ['Start bit: %s (Warning: Must be 0!)' % bit]])
 
         # Bits[46:46]: Transmitter bit (1 == host)
-        bit, self.bit_ss, self.bit_es = tb(5, 6)[0], tb(5, 6)[1], tb(5, 6)[2]
+        bit, self.ss_bit, self.es_bit = tb(5, 6)[0], tb(5, 6)[1], tb(5, 6)[2]
         if bit == 1:
             self.putb([134, ['Transmitter bit: %d' % bit]])
         else:
@@ -172,22 +126,22 @@ class Decoder(srd.Decoder):
 
         # Bits[45:40]: Command index (BCD; valid: 0-63)
         cmd = self.cmd_index = t[0] & 0x3f
-        self.bit_ss, self.bit_es = tb(5, 5)[1], tb(5, 0)[2]
+        self.ss_bit, self.es_bit = tb(5, 5)[1], tb(5, 0)[2]
         self.putb([134, ['Command: %s%d (%s)' % (s, cmd, self.cmd_name(cmd))]])
 
         # Bits[39:8]: Argument
         self.arg = (t[1] << 24) | (t[2] << 16) | (t[3] << 8) | t[4]
-        self.bit_ss, self.bit_es = tb(4, 7)[1], tb(1, 0)[2]
+        self.ss_bit, self.es_bit = tb(4, 7)[1], tb(1, 0)[2]
         self.putb([134, ['Argument: 0x%04x' % self.arg]])
 
         # Bits[7:1]: CRC7
         # TODO: Check CRC7.
         crc = t[5] >> 1
-        self.bit_ss, self.bit_es = tb(0, 7)[1], tb(0, 1)[2]
+        self.ss_bit, self.es_bit = tb(0, 7)[1], tb(0, 1)[2]
         self.putb([134, ['CRC7: 0x%01x' % crc]])
 
         # Bits[0:0]: End bit (always 1)
-        bit, self.bit_ss, self.bit_es = tb(0, 0)[0], tb(0, 0)[1], tb(0, 0)[2]
+        bit, self.ss_bit, self.es_bit = tb(0, 0)[0], tb(0, 0)[1], tb(0, 0)[2]
         self.putb([134, ['End bit: %d' % bit]])
         if bit == 1:
             self.putb([134, ['End bit: %d' % bit]])
@@ -212,8 +166,8 @@ class Decoder(srd.Decoder):
         # CMD1: SEND_OP_COND
         self.putc(1, 'Send HCS info and activate the card init process')
         hcs = (self.arg & (1 << 30)) >> 30
-        self.bit_ss = self.cmd_token_bits[5 - 4][6][1]
-        self.bit_es = self.cmd_token_bits[5 - 4][6][2]
+        self.ss_bit = self.cmd_token_bits[5 - 4][6][1]
+        self.es_bit = self.cmd_token_bits[5 - 4][6][2]
         self.putb([134, ['HCS: %d' % hcs]])
         self.state = 'GET RESPONSE R1'
 
@@ -221,14 +175,14 @@ class Decoder(srd.Decoder):
         # CMD9: SEND_CSD (128 bits / 16 bytes)
         self.putc(9, 'Ask card to send its card specific data (CSD)')
         if len(self.read_buf) == 0:
-            self.cmd_ss = self.ss
+            self.ss_cmd = self.ss
         self.read_buf.append(self.miso)
         # FIXME
         ### if len(self.read_buf) < 16:
         if len(self.read_buf) < 16 + 4:
             return
-        self.cmd_es = self.es
-        self.read_buf = self.read_buf[4:] ### TODO: Document or redo.
+        self.es_cmd = self.es
+        self.read_buf = self.read_buf[4:] # TODO: Document or redo.
         self.putx([9, ['CSD: %s' % self.read_buf]])
         # TODO: Decode all bits.
         self.read_buf = []
@@ -257,11 +211,11 @@ class Decoder(srd.Decoder):
         # CMD17: READ_SINGLE_BLOCK
         self.putc(17, 'Read a block from address 0x%04x' % self.arg)
         if len(self.read_buf) == 0:
-            self.cmd_ss = self.ss
+            self.ss_cmd = self.ss
         self.read_buf.append(self.miso)
         if len(self.read_buf) < self.blocklen + 2: # FIXME
             return
-        self.cmd_es = self.es
+        self.es_cmd = self.es
         self.read_buf = self.read_buf[2:] # FIXME
         self.putx([17, ['Block data: %s' % self.read_buf]])
         self.read_buf = []
@@ -332,12 +286,12 @@ class Decoder(srd.Decoder):
         # The R1 response token format (1 byte).
         # Sent by the card after every command except for SEND_STATUS.
 
-        self.cmd_ss, self.cmd_es = self.miso_bits[7][1], self.miso_bits[0][2]
+        self.ss_cmd, self.es_cmd = self.miso_bits[7][1], self.miso_bits[0][2]
         self.putx([65, ['R1: 0x%02x' % res]])
 
         def putbit(bit, data):
             b = self.miso_bits[bit]
-            self.bit_ss, self.bit_es = b[1], b[2]
+            self.ss_bit, self.es_bit = b[1], b[2]
             self.putb([134, data])
 
         # Bit 0: 'In idle state' bit
@@ -439,6 +393,3 @@ class Decoder(srd.Decoder):
             handle_response(miso)
 
             self.state = 'IDLE'
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/ir_nec/__init__.py b/decoders/spdif/__init__.py
similarity index 81%
copy from decoders/ir_nec/__init__.py
copy to decoders/spdif/__init__.py
index 84bf428..38363f0 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/spdif/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2014 Guenther Wenninger <robin at bitschubbser.org>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+S/PDIF (Sony/Philips Digital Interface Format) is a serial bus for
+transmitting audio data.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/spdif/pd.py b/decoders/spdif/pd.py
new file mode 100644
index 0000000..da3ca28
--- /dev/null
+++ b/decoders/spdif/pd.py
@@ -0,0 +1,257 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Guenther Wenninger <robin at bitschubbser.org>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'spdif'
+    name = 'S/PDIF'
+    longname = 'Sony/Philips Digital Interface Format'
+    desc = 'Serial bus for connecting digital audio devices.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['spdif']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    annotations = (
+        ('bitrate', 'Bitrate / baudrate'),
+        ('preamble', 'Preamble'),
+        ('bits', 'Bits'),
+        ('aux', 'Auxillary-audio-databits'),
+        ('samples', 'Audio Samples'),
+        ('validity', 'Data Valid'),
+        ('subcode', 'Subcode data'),
+        ('chan_stat', 'Channnel Status'),
+        ('parity', 'Parity Bit'),
+    )
+    annotation_rows = (
+        ('info', 'Info', (0, 1, 3, 5, 6, 7, 8)),
+        ('bits', 'Bits', (2,)),
+        ('samples', 'Samples', (4,)),
+    )
+
+    def putx(self, ss, es, data):
+        self.put(ss, es, self.out_ann, data)
+
+    def puty(self, data):
+        self.put(self.ss_edge, self.samplenum, self.out_ann, data)
+
+    def __init__(self):
+        self.state = 'GET FIRST PULSE WIDTH'
+        self.olddata = None
+        self.ss_edge = None
+        self.first_edge = True
+        self.pulse_width = 0
+
+        self.clocks = []
+        self.range1 = 0
+        self.range2 = 0
+
+        self.preamble_state = 0
+        self.preamble = []
+        self.seen_preamble = False
+        self.last_preamble = 0
+
+        self.first_one = True
+        self.subframe = []
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def get_pulse_type(self):
+        if self.range1 == 0 or self.range2 == 0:
+            return -1
+        if self.pulse_width >= self.range2:
+            return 2
+        elif self.pulse_width >= self.range1:
+            return 0
+        else:
+            return 1
+
+    def find_first_pulse_width(self):
+        if self.pulse_width != 0:
+            self.clocks.append(self.pulse_width)
+            self.state = 'GET SECOND PULSE WIDTH'
+
+    def find_second_pulse_width(self):
+        if self.pulse_width > (self.clocks[0] * 1.3) or \
+                self.pulse_width < (self.clocks[0] * 0.7):
+            self.clocks.append(self.pulse_width)
+            self.state = 'GET THIRD PULSE WIDTH'
+
+    def find_third_pulse_width(self):
+        if not ((self.pulse_width > (self.clocks[0] * 1.3) or \
+                self.pulse_width < (self.clocks[0] * 0.7)) \
+                and (self.pulse_width > (self.clocks[1] * 1.3) or \
+                self.pulse_width < (self.clocks[1] * 0.7))):
+            return
+
+        self.clocks.append(self.pulse_width)
+        self.clocks.sort()
+        self.range1 = (self.clocks[0] + self.clocks[1]) / 2
+        self.range2 = (self.clocks[1] + self.clocks[2]) / 2
+        spdif_bitrate = int(self.samplerate / (self.clocks[2] / 1.5))
+        self.ss_edge = 0
+
+        self.puty([0, ['Signal Bitrate: %d Mbit/s (=> %d kHz)' % \
+                  (spdif_bitrate, (spdif_bitrate/ (2 * 32)))]])
+
+        clock_period_nsec = 1000000000 / spdif_bitrate
+
+        self.last_preamble = self.samplenum
+
+        # We are done recovering the clock, now let's decode the data stream.
+        self.state = 'DECODE STREAM'
+
+    def decode_stream(self):
+        pulse = self.get_pulse_type()
+
+        if not self.seen_preamble:
+            # This is probably the start of a preamble, decode it.
+            if pulse == 2:
+                self.preamble.append(self.get_pulse_type())
+                self.state = 'DECODE PREAMBLE'
+                self.ss_edge = self.samplenum - self.pulse_width - 1
+            return
+
+        # We've seen a preamble.
+        if pulse == 1 and self.first_one:
+            self.first_one = False
+            self.subframe.append([pulse, self.samplenum - \
+                self.pulse_width - 1, self.samplenum])
+        elif pulse == 1 and not self.first_one:
+            self.subframe[-1][2] = self.samplenum
+            self.putx(self.subframe[-1][1], self.samplenum, [2, ['1']])
+            self.bitcount += 1
+            self.first_one = True
+        else:
+            self.subframe.append([pulse, self.samplenum - \
+                self.pulse_width - 1, self.samplenum])
+            self.putx(self.samplenum - self.pulse_width - 1,
+                      self.samplenum, [2, ['0']])
+            self.bitcount += 1
+
+        if self.bitcount == 28:
+            aux_audio_data = self.subframe[0:4]
+            sam, sam_rot = '', ''
+            for a in aux_audio_data:
+                sam = sam + str(a[0])
+                sam_rot = str(a[0]) + sam_rot
+            sample = self.subframe[4:24]
+            for s in sample:
+                sam = sam + str(s[0])
+                sam_rot = str(s[0]) + sam_rot
+            validity = self.subframe[24:25]
+            subcode_data = self.subframe[25:26]
+            channel_status = self.subframe[26:27]
+            parity = self.subframe[27:28]
+
+            self.putx(aux_audio_data[0][1], aux_audio_data[3][2], \
+                      [3, ['Aux 0x%x' % int(sam, 2), '0x%x' % int(sam, 2)]])
+            self.putx(sample[0][1], sample[19][2], \
+                      [3, ['Sample 0x%x' % int(sam, 2), '0x%x' % int(sam, 2)]])
+            self.putx(aux_audio_data[0][1], sample[19][2], \
+                      [4, ['Audio 0x%x' % int(sam_rot, 2), '0x%x' % int(sam_rot, 2)]])
+            if validity[0][0] == 0:
+                self.putx(validity[0][1], validity[0][2], [5, ['V']])
+            else:
+                self.putx(validity[0][1], validity[0][2], [5, ['E']])
+            self.putx(subcode_data[0][1], subcode_data[0][2],
+                [6, ['S: %d' % subcode_data[0][0]]])
+            self.putx(channel_status[0][1], channel_status[0][2],
+                [7, ['C: %d' % channel_status[0][0]]])
+            self.putx(parity[0][1], parity[0][2], [8, ['P: %d' % parity[0][0]]])
+
+            self.subframe = []
+            self.seen_preamble = False
+            self.bitcount = 0
+
+    def decode_preamble(self):
+        if self.preamble_state == 0:
+            self.preamble.append(self.get_pulse_type())
+            self.preamble_state = 1
+        elif self.preamble_state == 1:
+            self.preamble.append(self.get_pulse_type())
+            self.preamble_state = 2
+        elif self.preamble_state == 2:
+            self.preamble.append(self.get_pulse_type())
+            self.preamble_state = 0
+            self.state = 'DECODE STREAM'
+            if self.preamble == [2, 0, 1, 0]:
+                self.puty([1, ['Preamble W', 'W']])
+            elif self.preamble == [2, 2, 1, 1]:
+                self.puty([1, ['Preamble M', 'M']])
+            elif self.preamble == [2, 1, 1, 2]:
+                self.puty([1, ['Preamble B', 'B']])
+            else:
+                self.puty([1, ['Unknown Preamble', 'Unknown Prea.', 'U']])
+            self.preamble = []
+            self.seen_preamble = True
+            self.bitcount = 0
+            self.first_one = True
+
+        self.last_preamble = self.samplenum
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+
+        for (self.samplenum, pins) in data:
+            data = pins[0]
+
+            # Initialize self.olddata with the first sample value.
+            if self.olddata is None:
+                self.olddata = data
+                continue
+
+            # First we need to recover the clock.
+            if self.olddata == data:
+                self.pulse_width += 1
+                continue
+
+            # Found rising or falling edge.
+            if self.first_edge:
+                # Throw away first detected edge as it might be mangled data.
+                self.first_edge = False
+                self.pulse_width = 0
+            else:
+                if self.state == 'GET FIRST PULSE WIDTH':
+                    self.find_first_pulse_width()
+                elif self.state == 'GET SECOND PULSE WIDTH':
+                    self.find_second_pulse_width()
+                elif self.state == 'GET THIRD PULSE WIDTH':
+                    self.find_third_pulse_width()
+                elif self.state == 'DECODE STREAM':
+                    self.decode_stream()
+                elif self.state == 'DECODE PREAMBLE':
+                    self.decode_preamble()
+
+            self.pulse_width = 0
+
+            self.olddata = data
diff --git a/decoders/spi/__init__.py b/decoders/spi/__init__.py
index a1f0f1c..f76bb06 100644
--- a/decoders/spi/__init__.py
+++ b/decoders/spi/__init__.py
@@ -29,5 +29,4 @@ transitions where CS# is not asserted are ignored). If CS# is not supplied,
 data is decoded on every clock transition (depending on SPI mode).
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/spi/pd.py b/decoders/spi/pd.py
index 5bab8f7..ce007e2 100644
--- a/decoders/spi/pd.py
+++ b/decoders/spi/pd.py
@@ -20,6 +20,9 @@
 ##
 
 import sigrokdecode as srd
+from collections import namedtuple
+
+Data = namedtuple('Data', ['ss', 'es', 'val'])
 
 '''
 OUTPUT_PYTHON format:
@@ -28,16 +31,22 @@ Packet:
 [<ptype>, <data1>, <data2>]
 
 <ptype>:
- - 'DATA': <data1> contains the MISO data, <data2> contains the MOSI data.
+ - 'DATA': <data1> contains the MOSI data, <data2> contains the MISO data.
    The data is _usually_ 8 bits (but can also be fewer or more bits).
    Both data items are Python numbers (not strings), or None if the respective
    channel was not supplied.
- - 'BITS': <data1>/<data2> contain a list of bit values in this MISO/MOSI data
+ - 'BITS': <data1>/<data2> contain a list of bit values in this MOSI/MISO data
    item, and for each of those also their respective start-/endsample numbers.
- - 'CS CHANGE': <data1> is the old CS# pin value, <data2> is the new value.
-   Both data items are Python numbers (0/1), not strings.
+ - 'CS-CHANGE': <data1> is the old CS# pin value, <data2> is the new value.
+   Both data items are Python numbers (0/1), not strings. At the beginning of
+   the decoding a packet is generated with <data1> = None and <data2> being the
+   initial state of the CS# pin or None if the chip select pin is not supplied.
+ - 'TRANSFER': <data1>/<data2> contain a list of Data() namedtuples for each
+   byte transferred during this block of CS# asserted time. Each Data() has
+   fields ss, es, and val.
 
 Examples:
+ ['CS-CHANGE', None, 1]
  ['CS-CHANGE', 1, 0]
  ['DATA', 0xff, 0x3a]
  ['BITS', [[1, 80, 82], [1, 83, 84], [1, 85, 86], [1, 87, 88],
@@ -48,6 +57,8 @@ Examples:
  ['DATA', 0xa8, None]
  ['DATA', None, 0x55]
  ['CS-CHANGE', 0, 1]
+ ['TRANSFER', [Data(ss=80, es=96, val=0xff), ...],
+              [Data(ss=80, es=96, val=0x3a), ...]]
 '''
 
 # Key: (CPOL, CPHA). Value: SPI mode.
@@ -60,6 +71,12 @@ spi_mode = {
     (1, 1): 3, # Mode 3
 }
 
+class SamplerateError(Exception):
+    pass
+
+class ChannelError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'spi'
@@ -102,6 +119,10 @@ class Decoder(srd.Decoder):
         ('mosi-bits', 'MOSI bits', (3,)),
         ('other', 'Other', (4,)),
     )
+    binary = (
+        ('miso', 'MISO'),
+        ('mosi', 'MOSI'),
+    )
 
     def __init__(self):
         self.samplerate = None
@@ -110,13 +131,16 @@ class Decoder(srd.Decoder):
         self.misodata = self.mosidata = 0
         self.misobits = []
         self.mosibits = []
-        self.startsample = -1
+        self.misobytes = []
+        self.mosibytes = []
+        self.ss_block = -1
         self.samplenum = -1
+        self.ss_transfer = -1
         self.cs_was_deasserted = False
-        self.oldcs = -1
+        self.oldcs = None
         self.oldpins = None
         self.have_cs = self.have_miso = self.have_mosi = None
-        self.state = 'IDLE'
+        self.no_cs_notification = False
 
     def metadata(self, key, value):
         if key == srd.SRD_CONF_SAMPLERATE:
@@ -125,11 +149,13 @@ class Decoder(srd.Decoder):
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
         self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
         self.out_bitrate = self.register(srd.OUTPUT_META,
                 meta=(int, 'Bitrate', 'Bitrate during transfers'))
+        self.bw = (self.options['wordsize'] + 7) // 8
 
     def putw(self, data):
-        self.put(self.startsample, self.samplenum, self.out_ann, data)
+        self.put(self.ss_block, self.samplenum, self.out_ann, data)
 
     def putdata(self):
         # Pass MISO and MOSI bits and then data to the next PD up the stack.
@@ -140,12 +166,21 @@ class Decoder(srd.Decoder):
 
         if self.have_miso:
             ss, es = self.misobits[-1][1], self.misobits[0][2]
+            bdata = so.to_bytes(self.bw, byteorder='big')
+            self.put(ss, es, self.out_binary, [0, bdata])
         if self.have_mosi:
             ss, es = self.mosibits[-1][1], self.mosibits[0][2]
+            bdata = si.to_bytes(self.bw, byteorder='big')
+            self.put(ss, es, self.out_binary, [1, bdata])
 
         self.put(ss, es, self.out_python, ['BITS', si_bits, so_bits])
         self.put(ss, es, self.out_python, ['DATA', si, so])
 
+        if self.have_miso:
+            self.misobytes.append(Data(ss=ss, es=es, val=so))
+        if self.have_mosi:
+            self.mosibytes.append(Data(ss=ss, es=es, val=si))
+
         # Bit annotations.
         if self.have_miso:
             for bit in self.misobits:
@@ -167,16 +202,16 @@ class Decoder(srd.Decoder):
         self.mosibits = [] if self.have_mosi else None
         self.bitcount = 0
 
+    def cs_asserted(self, cs):
+        active_low = (self.options['cs_polarity'] == 'active-low')
+        return (cs == 0) if active_low else (cs == 1)
+
     def handle_bit(self, miso, mosi, clk, cs):
         # If this is the first bit of a dataword, save its sample number.
         if self.bitcount == 0:
-            self.startsample = self.samplenum
-            self.cs_was_deasserted = False
-            if self.have_cs:
-                active_low = (self.options['cs_polarity'] == 'active-low')
-                deasserted = (cs == 1) if active_low else (cs == 0)
-                if deasserted:
-                    self.cs_was_deasserted = True
+            self.ss_block = self.samplenum
+            self.cs_was_deasserted = \
+                not self.cs_asserted(cs) if self.have_cs else False
 
         ws = self.options['wordsize']
 
@@ -222,9 +257,9 @@ class Decoder(srd.Decoder):
 
         # Meta bitrate.
         elapsed = 1 / float(self.samplerate)
-        elapsed *= (self.samplenum - self.startsample + 1)
+        elapsed *= (self.samplenum - self.ss_block + 1)
         bitrate = int(1 / elapsed * self.options['wordsize'])
-        self.put(self.startsample, self.samplenum, self.out_bitrate, bitrate)
+        self.put(self.ss_block, self.samplenum, self.out_bitrate, bitrate)
 
         if self.have_cs and self.cs_was_deasserted:
             self.putw([4, ['CS# was deasserted during this data word!']])
@@ -237,9 +272,22 @@ class Decoder(srd.Decoder):
             self.put(self.samplenum, self.samplenum, self.out_python,
                      ['CS-CHANGE', self.oldcs, cs])
             self.oldcs = cs
+
+            if self.cs_asserted(cs):
+                self.ss_transfer = self.samplenum
+                self.misobytes = []
+                self.mosibytes = []
+            else:
+                self.put(self.ss_transfer, self.samplenum, self.out_python,
+                    ['TRANSFER', self.mosibytes, self.misobytes])
+
             # Reset decoder state when CS# changes (and the CS# pin is used).
             self.reset_decoder_state()
 
+        # We only care about samples if CS# is asserted.
+        if self.have_cs and not self.cs_asserted(cs):
+            return
+
         # Ignore sample if the clock pin hasn't changed.
         if clk == self.oldclk:
             return
@@ -261,8 +309,8 @@ class Decoder(srd.Decoder):
         self.handle_bit(miso, mosi, clk, cs)
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         # Either MISO or MOSI can be omitted (but not both). CS# is optional.
         for (self.samplenum, pins) in data:
 
@@ -276,11 +324,11 @@ class Decoder(srd.Decoder):
 
             # Either MISO or MOSI (but not both) can be omitted.
             if not (self.have_miso or self.have_mosi):
-                raise Exception('Either MISO or MOSI (or both) pins required.')
+                raise ChannelError('Either MISO or MOSI (or both) pins required.')
 
-            # State machine.
-            if self.state == 'IDLE':
-                self.find_clk_edge(miso, mosi, clk, cs)
-            else:
-                raise Exception('Invalid state: %s' % self.state)
+            # Tell stacked decoders that we don't have a CS# signal.
+            if not self.no_cs_notification and not self.have_cs:
+                self.put(0, 0, self.out_python, ['CS-CHANGE', None, None])
+                self.no_cs_notification = True
 
+            self.find_clk_edge(miso, mosi, clk, cs)
diff --git a/decoders/mx25lxx05d/__init__.py b/decoders/spiflash/__init__.py
similarity index 79%
rename from decoders/mx25lxx05d/__init__.py
rename to decoders/spiflash/__init__.py
index 71d7b3c..6ffb4da 100644
--- a/decoders/mx25lxx05d/__init__.py
+++ b/decoders/spiflash/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2015 Uwe Hermann <uwe at hermann-uwe.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
@@ -19,14 +19,13 @@
 ##
 
 '''
-This decoder stacks on top of the 'spi' PD and decodes the Macronix
-MX25Lxx05D SPI (NOR) flash chip protocol.
+This decoder stacks on top of the 'spi' PD and decodes the xx25 series
+SPI (NOR) flash chip protocol.
 
-It works for the MX25L1605D/MX25L3205D/MX25L6405D.
+It currently supports the MX25L1605D/MX25L3205D/MX25L6405D.
 
 Details:
 http://www.macronix.com/QuickPlace/hq/PageLibrary4825740B00298A3B.nsf/h_Index/3F21BAC2E121E17848257639003A3146/$File/MX25L1605D-3205D-6405D-1.5.pdf
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/spiflash/lists.py b/decoders/spiflash/lists.py
new file mode 100644
index 0000000..ba9f2c2
--- /dev/null
+++ b/decoders/spiflash/lists.py
@@ -0,0 +1,112 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+from collections import OrderedDict
+
+# OrderedDict which maps command IDs to their names and descriptions.
+# Please keep this sorted by command ID.
+# Don't forget to update 'Ann' in pd.py if you add/remove items here.
+cmds = OrderedDict([
+    (0x01, ('WRSR', 'Write status register')),
+    (0x02, ('PP', 'Page program')),
+    (0x03, ('READ', 'Read data')),
+    (0x04, ('WRDI', 'Write disable')),
+    (0x05, ('RDSR', 'Read status register')),
+    (0x06, ('WREN', 'Write enable')),
+    (0x0b, ('FAST/READ', 'Fast read data')),
+    (0x20, ('SE', 'Sector erase')),
+    (0x2b, ('RDSCUR', 'Read security register')),
+    (0x2f, ('WRSCUR', 'Write security register')),
+    (0x35, ('RDSR2', 'Read status register 2')),
+    (0x60, ('CE', 'Chip erase')),
+    (0x70, ('ESRY', 'Enable SO to output RY/BY#')),
+    (0x80, ('DSRY', 'Disable SO to output RY/BY#')),
+    (0x90, ('REMS', 'Read electronic manufacturer & device ID')),
+    (0x9f, ('RDID', 'Read identification')),
+    (0xab, ('RDP/RES', 'Release from deep powerdown / Read electronic ID')),
+    (0xad, ('CP', 'Continuously program mode')),
+    (0xb1, ('ENSO', 'Enter secured OTP')),
+    (0xb9, ('DP', 'Deep power down')),
+    (0xbb, ('2READ', '2x I/O read')), # a.k.a. "Fast read dual I/O".
+    (0xc1, ('EXSO', 'Exit secured OTP')),
+    (0xc7, ('CE2', 'Chip erase')), # Alternative command ID
+    (0xd8, ('BE', 'Block erase')),
+    (0xef, ('REMS2', 'Read ID for 2x I/O mode')),
+])
+
+device_name = {
+    'fidelix': {
+        0x15: 'FM25Q32',
+    },
+    'macronix': {
+        0x14: 'MX25L1605D',
+        0x15: 'MX25L3205D',
+        0x16: 'MX25L6405D',
+    },
+}
+
+chips = {
+    # FIDELIX
+    'fidelix_fm25q32': {
+        'vendor': 'FIDELIX',
+        'model': 'FM25Q32',
+        'res_id': 0x15,
+        'rems_id': 0xa115,
+        'rems2_id': 0xa115,
+        'rdid_id': 0xa14016,
+        'page_size': 256,
+        'sector_size': 4 * 1024,
+        'block_size': 64 * 1024,
+    },
+    # Macronix
+    'macronix_mx25l1605d': {
+        'vendor': 'Macronix',
+        'model': 'MX25L1605D',
+        'res_id': 0x14,
+        'rems_id': 0xc214,
+        'rems2_id': 0xc214,
+        'rdid_id': 0xc22015,
+        'page_size': 256,
+        'sector_size': 4 * 1024,
+        'block_size': 64 * 1024,
+    },
+    'macronix_mx25l3205d': {
+        'vendor': 'Macronix',
+        'model': 'MX25L3205D',
+        'res_id': 0x15,
+        'rems_id': 0xc215,
+        'rems2_id': 0xc215,
+        'rdid_id': 0xc22016,
+        'page_size': 256,
+        'sector_size': 4 * 1024,
+        'block_size': 64 * 1024,
+    },
+    'macronix_mx25l6405d': {
+        'vendor': 'Macronix',
+        'model': 'MX25L6405D',
+        'res_id': 0x16,
+        'rems_id': 0xc216,
+        'rems2_id': 0xc216,
+        'rdid_id': 0xc22017,
+        'page_size': 256,
+        'sector_size': 4 * 1024,
+        'block_size': 64 * 1024,
+    },
+}
diff --git a/decoders/spiflash/pd.py b/decoders/spiflash/pd.py
new file mode 100644
index 0000000..bc5f9ca
--- /dev/null
+++ b/decoders/spiflash/pd.py
@@ -0,0 +1,485 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2011-2016 Uwe Hermann <uwe at hermann-uwe.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from .lists import *
+
+L = len(cmds)
+
+# Don't forget to keep this in sync with 'cmds' is lists.py.
+class Ann:
+    WRSR, PP, READ, WRDI, RDSR, WREN, FAST_READ, SE, RDSCUR, WRSCUR, \
+    RDSR2, CE, ESRY, DSRY, REMS, RDID, RDP_RES, CP, ENSO, DP, READ2X, \
+    EXSO, CE2, BE, REMS2, \
+    BIT, FIELD, WARN = range(L + 3)
+
+def cmd_annotation_classes():
+    return tuple([tuple([cmd[0].lower(), cmd[1]]) for cmd in cmds.values()])
+
+def decode_dual_bytes(sio0, sio1):
+    # Given a byte in SIO0 (MOSI) of even bits and a byte in
+    # SIO1 (MISO) of odd bits, return a tuple of two bytes.
+    def combine_byte(even, odd):
+        result = 0
+        for bit in range(4):
+            if even & (1 << bit):
+                result |= 1 << (bit*2)
+            if odd & (1 << bit):
+                result |= 1 << ((bit*2) + 1)
+        return result
+    return (combine_byte(sio0 >> 4, sio1 >> 4), combine_byte(sio0, sio1))
+
+def decode_status_reg(data):
+    # TODO: Additional per-bit(s) self.put() calls with correct start/end.
+
+    # Bits[0:0]: WIP (write in progress)
+    s = 'W' if (data & (1 << 0)) else 'No w'
+    ret = '%srite operation in progress.\n' % s
+
+    # Bits[1:1]: WEL (write enable latch)
+    s = '' if (data & (1 << 1)) else 'not '
+    ret += 'Internal write enable latch is %sset.\n' % s
+
+    # Bits[5:2]: Block protect bits
+    # TODO: More detailed decoding (chip-dependent).
+    ret += 'Block protection bits (BP3-BP0): 0x%x.\n' % ((data & 0x3c) >> 2)
+
+    # Bits[6:6]: Continuously program mode (CP mode)
+    s = '' if (data & (1 << 6)) else 'not '
+    ret += 'Device is %sin continuously program mode (CP mode).\n' % s
+
+    # Bits[7:7]: SRWD (status register write disable)
+    s = 'not ' if (data & (1 << 7)) else ''
+    ret += 'Status register writes are %sallowed.\n' % s
+
+    return ret
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'spiflash'
+    name = 'SPI flash'
+    longname = 'SPI flash chips'
+    desc = 'xx25 series SPI (NOR) flash chip protocol.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['spiflash']
+    annotations = cmd_annotation_classes() + (
+        ('bit', 'Bit'),
+        ('field', 'Field'),
+        ('warning', 'Warning'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (L + 0,)),
+        ('fields', 'Fields', (L + 1,)),
+        ('commands', 'Commands', tuple(range(len(cmds)))),
+        ('warnings', 'Warnings', (L + 2,)),
+    )
+    options = (
+        {'id': 'chip', 'desc': 'Chip', 'default': tuple(chips.keys())[0],
+            'values': tuple(chips.keys())},
+        {'id': 'format', 'desc': 'Data format', 'default': 'hex',
+            'values': ('hex', 'ascii')},
+    )
+
+    def __init__(self):
+        self.device_id = -1
+        self.on_end_transaction = None
+        self.end_current_transaction()
+
+        # Build dict mapping command keys to handler functions. Each
+        # command in 'cmds' (defined in lists.py) has a matching
+        # handler self.handle_<shortname>.
+        def get_handler(cmd):
+            s = 'handle_%s' % cmds[cmd][0].lower().replace('/', '_')
+            return getattr(self, s)
+        self.cmd_handlers = dict((cmd, get_handler(cmd)) for cmd in cmds.keys())
+
+    def end_current_transaction(self):
+        if self.on_end_transaction is not None: # Callback for CS# transition.
+            self.on_end_transaction()
+            self.on_end_transaction = None
+        self.state = None
+        self.cmdstate = 1
+        self.addr = 0
+        self.data = []
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.chip = chips[self.options['chip']]
+        self.vendor = self.options['chip'].split('_')[0]
+
+    def putx(self, data):
+        # Simplification, most annotations span exactly one SPI byte/packet.
+        self.put(self.ss, self.es, self.out_ann, data)
+
+    def putf(self, data):
+        self.put(self.ss_field, self.es_field, self.out_ann, data)
+
+    def putc(self, data):
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
+
+    def device(self):
+        return device_name[self.vendor].get(self.device_id, 'Unknown')
+
+    def vendor_device(self):
+        return '%s %s' % (self.chip['vendor'], self.device())
+
+    def cmd_ann_list(self):
+        x, s = cmds[self.state][0], cmds[self.state][1]
+        return ['Command: %s (%s)' % (s, x), 'Command: %s' % s,
+                'Cmd: %s' % s, 'Cmd: %s' % x, x]
+
+    def cmd_vendor_dev_list(self):
+        c, d = cmds[self.state], 'Device = %s' % self.vendor_device()
+        return ['%s (%s): %s' % (c[1], c[0], d), '%s: %s' % (c[1], d),
+                '%s: %s' % (c[0], d), d, self.vendor_device()]
+
+    def emit_cmd_byte(self):
+        self.ss_cmd = self.ss
+        self.putx([Ann.FIELD, self.cmd_ann_list()])
+        self.addr = 0
+
+    def emit_addr_bytes(self, mosi):
+        self.addr |= (mosi << ((4 - self.cmdstate) * 8))
+        b = ((3 - (self.cmdstate - 2)) * 8) - 1
+        self.putx([Ann.BIT,
+            ['Address bits %d..%d: 0x%02x' % (b, b - 7, mosi),
+             'Addr bits %d..%d: 0x%02x' % (b, b - 7, mosi),
+             'Addr bits %d..%d' % (b, b - 7), 'A%d..A%d' % (b, b - 7)]])
+        if self.cmdstate == 2:
+            self.ss_field = self.ss
+        if self.cmdstate == 4:
+            self.es_field = self.es
+            self.putf([Ann.FIELD, ['Address: 0x%06x' % self.addr,
+                'Addr: 0x%06x' % self.addr, '0x%06x' % self.addr]])
+
+    def handle_wren(self, mosi, miso):
+        self.putx([Ann.WREN, self.cmd_ann_list()])
+        self.state = None
+
+    def handle_wrdi(self, mosi, miso):
+        pass # TODO
+
+    def handle_rdid(self, mosi, miso):
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate == 2:
+            # Byte 2: Slave sends the JEDEC manufacturer ID.
+            self.putx([Ann.FIELD, ['Manufacturer ID: 0x%02x' % miso]])
+        elif self.cmdstate == 3:
+            # Byte 3: Slave sends the memory type.
+            self.putx([Ann.FIELD, ['Memory type: 0x%02x' % miso]])
+        elif self.cmdstate == 4:
+            # Byte 4: Slave sends the device ID.
+            self.device_id = miso
+            self.putx([Ann.FIELD, ['Device ID: 0x%02x' % miso]])
+
+        if self.cmdstate == 4:
+            self.es_cmd = self.es
+            self.putc([Ann.RDID, self.cmd_vendor_dev_list()])
+            self.state = None
+        else:
+            self.cmdstate += 1
+
+    def handle_rdsr(self, mosi, miso):
+        # Read status register: Master asserts CS#, sends RDSR command,
+        # reads status register byte. If CS# is kept asserted, the status
+        # register can be read continuously / multiple times in a row.
+        # When done, the master de-asserts CS# again.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate >= 2:
+            # Bytes 2-x: Slave sends status register as long as master clocks.
+            self.es_cmd = self.es
+            self.putx([Ann.BIT, [decode_status_reg(miso)]])
+            self.putx([Ann.FIELD, ['Status register']])
+            self.putc([Ann.RDSR, self.cmd_ann_list()])
+        self.cmdstate += 1
+
+    def handle_rdsr2(self, mosi, miso):
+        # Read status register 2: Master asserts CS#, sends RDSR2 command,
+        # reads status register 2 byte. If CS# is kept asserted, the status
+        # register 2 can be read continuously / multiple times in a row.
+        # When done, the master de-asserts CS# again.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate >= 2:
+            # Bytes 2-x: Slave sends status register 2 as long as master clocks.
+            self.es_cmd = self.es
+            # TODO: Decode status register 2 correctly.
+            self.putx([Ann.BIT, [decode_status_reg(miso)]])
+            self.putx([Ann.FIELD, ['Status register 2']])
+            self.putc([Ann.RDSR2, self.cmd_ann_list()])
+        self.cmdstate += 1
+
+    def handle_wrsr(self, mosi, miso):
+        # Write status register: Master asserts CS#, sends WRSR command,
+        # writes 1 or 2 status register byte(s).
+        # When done, the master de-asserts CS# again. If this doesn't happen
+        # the WRSR command will not be executed.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate == 2:
+            # Byte 2: Master sends status register 1.
+            self.putx([Ann.BIT, [decode_status_reg(miso)]])
+            self.putx([Ann.FIELD, ['Status register 1']])
+        elif self.cmdstate == 3:
+            # Byte 3: Master sends status register 2.
+            # TODO: Decode status register 2 correctly.
+            self.putx([Ann.BIT, [decode_status_reg(miso)]])
+            self.putx([Ann.FIELD, ['Status register 2']])
+            self.es_cmd = self.es
+            self.putc([Ann.WRSR, self.cmd_ann_list()])
+        self.cmdstate += 1
+
+    def handle_read(self, mosi, miso):
+        # Read data bytes: Master asserts CS#, sends READ command, sends
+        # 3-byte address, reads >= 1 data bytes, de-asserts CS#.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3, 4):
+            # Bytes 2/3/4: Master sends read address (24bits, MSB-first).
+            self.emit_addr_bytes(mosi)
+        elif self.cmdstate >= 5:
+            # Bytes 5-x: Master reads data bytes (until CS# de-asserted).
+            self.es_field = self.es # Will be overwritten for each byte.
+            if self.cmdstate == 5:
+                self.ss_field = self.ss
+                self.on_end_transaction = lambda: self.output_data_block('Data', Ann.READ)
+            self.data.append(miso)
+        self.cmdstate += 1
+
+    def handle_fast_read(self, mosi, miso):
+        # Fast read: Master asserts CS#, sends FAST READ command, sends
+        # 3-byte address + 1 dummy byte, reads >= 1 data bytes, de-asserts CS#.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3, 4):
+            # Bytes 2/3/4: Master sends read address (24bits, MSB-first).
+            self.emit_addr_bytes(mosi)
+        elif self.cmdstate == 5:
+            self.putx([Ann.BIT, ['Dummy byte: 0x%02x' % mosi]])
+        elif self.cmdstate >= 6:
+            # Bytes 6-x: Master reads data bytes (until CS# de-asserted).
+            self.es_field = self.es # Will be overwritten for each byte.
+            if self.cmdstate == 6:
+                self.ss_field = self.ss
+                self.on_end_transaction = lambda: self.output_data_block('Data', Ann.FAST_READ)
+            self.data.append(miso)
+        self.cmdstate += 1
+
+    def handle_2read(self, mosi, miso):
+        # 2x I/O read (fast read dual I/O): Master asserts CS#, sends 2READ
+        # command, sends 3-byte address + 1 dummy byte, reads >= 1 data bytes,
+        # de-asserts CS#. All data after the command is sent via two I/O pins.
+        # MOSI = SIO0 = even bits, MISO = SIO1 = odd bits.
+        if self.cmdstate != 1:
+            b1, b2 = decode_dual_bytes(mosi, miso)
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate == 2:
+            # Bytes 2/3(/4): Master sends read address (24bits, MSB-first).
+            # Handle bytes 2 and 3 here.
+            self.emit_addr_bytes(b1)
+            self.cmdstate = 3
+            self.emit_addr_bytes(b2)
+        elif self.cmdstate == 4:
+            # Byte 5: Dummy byte. Also handle byte 4 (address LSB) here.
+            self.emit_addr_bytes(b1)
+            self.cmdstate = 5
+            self.putx([Ann.BIT, ['Dummy byte: 0x%02x' % b2]])
+        elif self.cmdstate >= 6:
+            # Bytes 6-x: Master reads data bytes (until CS# de-asserted).
+            self.es_field = self.es # Will be overwritten for each byte.
+            if self.cmdstate == 6:
+                self.ss_field = self.ss
+                self.on_end_transaction = lambda: self.output_data_block('Data', Ann.READ2X)
+            self.data.append(b1)
+            self.data.append(b2)
+        self.cmdstate += 1
+
+    # TODO: Warn/abort if we don't see the necessary amount of bytes.
+    # TODO: Warn if WREN was not seen before.
+    def handle_se(self, mosi, miso):
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3, 4):
+            # Bytes 2/3/4: Master sends sector address (24bits, MSB-first).
+            self.emit_addr_bytes(mosi)
+
+        if self.cmdstate == 4:
+            self.es_cmd = self.es
+            d = 'Erase sector %d (0x%06x)' % (self.addr, self.addr)
+            self.putc([Ann.SE, [d]])
+            # TODO: Max. size depends on chip, check that too if possible.
+            if self.addr % 4096 != 0:
+                # Sector addresses must be 4K-aligned (same for all 3 chips).
+                self.putc([Ann.WARN, ['Warning: Invalid sector address!']])
+            self.state = None
+        else:
+            self.cmdstate += 1
+
+    def handle_be(self, mosi, miso):
+        pass # TODO
+
+    def handle_ce(self, mosi, miso):
+        pass # TODO
+
+    def handle_ce2(self, mosi, miso):
+        pass # TODO
+
+    def handle_pp(self, mosi, miso):
+        # Page program: Master asserts CS#, sends PP command, sends 3-byte
+        # page address, sends >= 1 data bytes, de-asserts CS#.
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3, 4):
+            # Bytes 2/3/4: Master sends page address (24bits, MSB-first).
+            self.emit_addr_bytes(mosi)
+        elif self.cmdstate >= 5:
+            # Bytes 5-x: Master sends data bytes (until CS# de-asserted).
+            self.es_field = self.es # Will be overwritten for each byte.
+            if self.cmdstate == 5:
+                self.ss_field = self.ss
+                self.on_end_transaction = lambda: self.output_data_block('Data', Ann.PP)
+            self.data.append(mosi)
+        self.cmdstate += 1
+
+    def handle_cp(self, mosi, miso):
+        pass # TODO
+
+    def handle_dp(self, mosi, miso):
+        pass # TODO
+
+    def handle_rdp_res(self, mosi, miso):
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3, 4):
+            # Bytes 2/3/4: Master sends three dummy bytes.
+            self.putx([Ann.FIELD, ['Dummy byte: %02x' % mosi]])
+        elif self.cmdstate == 5:
+            # Byte 5: Slave sends device ID.
+            self.es_cmd = self.es
+            self.device_id = miso
+            self.putx([Ann.FIELD, ['Device ID: %s' % self.device()]])
+            d = 'Device = %s' % self.vendor_device()
+            self.putc([Ann.RDP_RES, self.cmd_vendor_dev_list()])
+            self.state = None
+        self.cmdstate += 1
+
+    def handle_rems(self, mosi, miso):
+        if self.cmdstate == 1:
+            # Byte 1: Master sends command ID.
+            self.emit_cmd_byte()
+        elif self.cmdstate in (2, 3):
+            # Bytes 2/3: Master sends two dummy bytes.
+            self.putx([Ann.FIELD, ['Dummy byte: 0x%02x' % mosi]])
+        elif self.cmdstate == 4:
+            # Byte 4: Master sends 0x00 or 0x01.
+            # 0x00: Master wants manufacturer ID as first reply byte.
+            # 0x01: Master wants device ID as first reply byte.
+            self.manufacturer_id_first = True if (mosi == 0x00) else False
+            d = 'manufacturer' if (mosi == 0x00) else 'device'
+            self.putx([Ann.FIELD, ['Master wants %s ID first' % d]])
+        elif self.cmdstate == 5:
+            # Byte 5: Slave sends manufacturer ID (or device ID).
+            self.ids = [miso]
+            d = 'Manufacturer' if self.manufacturer_id_first else 'Device'
+            self.putx([Ann.FIELD, ['%s ID: 0x%02x' % (d, miso)]])
+        elif self.cmdstate == 6:
+            # Byte 6: Slave sends device ID (or manufacturer ID).
+            self.ids.append(miso)
+            d = 'Device' if self.manufacturer_id_first else 'Manufacturer'
+            self.putx([Ann.FIELD, ['%s ID: 0x%02x' % (d, miso)]])
+
+        if self.cmdstate == 6:
+            id = self.ids[1] if self.manufacturer_id_first else self.ids[0]
+            self.device_id = id
+            self.es_cmd = self.es
+            self.putc([Ann.REMS, self.cmd_vendor_dev_list()])
+            self.state = None
+        else:
+            self.cmdstate += 1
+
+    def handle_rems2(self, mosi, miso):
+        pass # TODO
+
+    def handle_enso(self, mosi, miso):
+        pass # TODO
+
+    def handle_exso(self, mosi, miso):
+        pass # TODO
+
+    def handle_rdscur(self, mosi, miso):
+        pass # TODO
+
+    def handle_wrscur(self, mosi, miso):
+        pass # TODO
+
+    def handle_esry(self, mosi, miso):
+        pass # TODO
+
+    def handle_dsry(self, mosi, miso):
+        pass # TODO
+
+    def output_data_block(self, label, idx):
+        # Print accumulated block of data
+        # (called on CS# de-assert via self.on_end_transaction callback).
+        self.es_cmd = self.es # End on the CS# de-assert sample.
+        if self.options['format'] == 'hex':
+            s = ' '.join([('%02x' % b) for b in self.data])
+        else:
+            s = ''.join(map(chr, self.data))
+        self.putf([Ann.FIELD, ['%s (%d bytes)' % (label, len(self.data))]])
+        self.putc([idx, ['%s (addr 0x%06x, %d bytes): %s' % \
+                   (cmds[self.state][1], self.addr, len(self.data), s)]])
+
+    def decode(self, ss, es, data):
+        ptype, mosi, miso = data
+
+        self.ss, self.es = ss, es
+
+        if ptype == 'CS-CHANGE':
+            self.end_current_transaction()
+
+        if ptype != 'DATA':
+            return
+
+        # If we encountered a known chip command, enter the resp. state.
+        if self.state is None:
+            self.state = mosi
+            self.cmdstate = 1
+
+        # Handle commands.
+        try:
+            self.cmd_handlers[self.state](mosi, miso)
+        except KeyError:
+            self.putx([Ann.BIT, ['Unknown command: 0x%02x' % mosi]])
+            self.state = None
diff --git a/decoders/dcf77/__init__.py b/decoders/ssi32/__init__.py
similarity index 73%
copy from decoders/dcf77/__init__.py
copy to decoders/ssi32/__init__.py
index 04805c2..fb7b4ed 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/ssi32/__init__.py
@@ -1,7 +1,10 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Robert Bosch Car Multimedia GmbH
+## Authors: Oleksij Rempel
+##              <fixed-term.Oleksij.Rempel at de.bosch.com>
+##              <linux at rempel-privat.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
@@ -19,12 +22,8 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
-
-Details:
-http://en.wikipedia.org/wiki/DCF77
+This decoder stacks on top of the 'spi' PD and decodes the Bosch
+SSI32 protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/ssi32/pd.py b/decoders/ssi32/pd.py
new file mode 100644
index 0000000..8c68e0d
--- /dev/null
+++ b/decoders/ssi32/pd.py
@@ -0,0 +1,124 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Robert Bosch Car Multimedia GmbH
+## Authors: Oleksij Rempel
+##              <fixed-term.Oleksij.Rempel at de.bosch.com>
+##              <linux at rempel-privat.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'ssi32'
+    name = 'SSI32'
+    longname = 'Synchronous Serial Interface (32bit)'
+    desc = 'Synchronous Serial Interface (32bit) protocol.'
+    license = 'gplv2+'
+    inputs = ['spi']
+    outputs = ['ssi32']
+    options = (
+        {'id': 'msgsize', 'desc': 'Message size', 'default': 64},
+    )
+    annotations = (
+        ('ctrl-tx', 'CTRL TX'),
+        ('ack-tx', 'ACK TX'),
+        ('ctrl-rx', 'CTRL RX'),
+        ('ack-rx', 'ACK RX'),
+    )
+    annotation_rows = (
+        ('tx', 'TX', (0, 1)),
+        ('rx', 'RX', (2, 3)),
+    )
+
+    def __init__(self):
+        self.ss_cmd, self.es_cmd = 0, 0
+        self.mosi_bytes = []
+        self.miso_bytes = []
+        self.es_array = []
+        self.rx_size = 0
+        self.tx_size = 0
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putx(self, data):
+        self.put(self.ss_cmd, self.es_cmd, self.out_ann, data)
+
+    def reset(self):
+        self.mosi_bytes = []
+        self.miso_bytes = []
+        self.es_array = []
+
+    def handle_ack(self):
+        # Only first byte should have ACK data, other 3 bytes are reserved.
+        self.es_cmd = self.es_array[0]
+        self.putx([1, ['> ACK:0x%02x' % (self.mosi_bytes[0])]])
+        self.putx([3, ['< ACK:0x%02x' % (self.miso_bytes[0])]])
+
+    def handle_ctrl(self):
+        mosi = miso = ''
+        self.tx_size = self.mosi_bytes[2]
+        self.rx_size = self.miso_bytes[2]
+
+        if self.tx_size > 0:
+            mosi = ', DATA:0x' + ''.join(format(x, '02x') for x in self.mosi_bytes[4:self.tx_size + 4])
+        if self.rx_size > 0:
+            miso = ', DATA:0x' + ''.join(format(x, '02x') for x in self.miso_bytes[4:self.rx_size + 4])
+
+        self.es_cmd = self.es_array[self.tx_size + 3]
+        self.putx([0, ['> CTRL:0x%02x, LUN:0x%02x, SIZE:0x%02x, CRC:0x%02x%s'
+                   % (self.mosi_bytes[0], self.mosi_bytes[1],
+                      self.mosi_bytes[2], self.mosi_bytes[3], mosi)]])
+
+        self.es_cmd = self.es_array[self.rx_size + 3]
+        self.putx([2, ['< CTRL:0x%02x, LUN:0x%02x, SIZE:0x%02x, CRC:0x%02x%s'
+                   % (self.miso_bytes[0], self.miso_bytes[1],
+                      self.miso_bytes[2], self.miso_bytes[3], miso)]])
+
+    def decode(self, ss, es, data):
+        ptype = data[0]
+        if ptype == 'CS-CHANGE':
+            self.reset()
+            return
+
+        # Don't care about anything else.
+        if ptype != 'DATA':
+            return
+        mosi, miso = data[1:]
+
+        self.ss, self.es = ss, es
+
+        if len(self.mosi_bytes) == 0:
+            self.ss_cmd = ss
+        self.mosi_bytes.append(mosi)
+        self.miso_bytes.append(miso)
+        self.es_array.append(es)
+
+        if self.mosi_bytes[0] & 0x80:
+            if len(self.mosi_bytes) < 4:
+                return
+
+            self.handle_ack()
+            self.reset()
+        else:
+            if len(self.mosi_bytes) < self.options['msgsize']:
+                return
+
+            self.handle_ctrl()
+            self.reset()
diff --git a/decoders/rtc8564/__init__.py b/decoders/stepper_motor/__init__.py
similarity index 78%
copy from decoders/rtc8564/__init__.py
copy to decoders/stepper_motor/__init__.py
index 9a397b1..222d393 100644
--- a/decoders/rtc8564/__init__.py
+++ b/decoders/stepper_motor/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
 ##
 ## 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
@@ -19,9 +19,8 @@
 ##
 
 '''
-This decoder stacks on top of the 'i2c' PD and decodes the Epson
-RTC-8564 JE/NB real-time clock (RTC) protocol.
+This PD decodes the stepper motor controller signals (step / dir) and
+shows the step speed and absolute position of the stepper motor.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/stepper_motor/pd.py b/decoders/stepper_motor/pd.py
new file mode 100644
index 0000000..7664fc4
--- /dev/null
+++ b/decoders/stepper_motor/pd.py
@@ -0,0 +1,97 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Petteri Aimonen <jpa at sigrok.mail.kapsi.fi>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'stepper_motor'
+    name = 'Stepper motor'
+    longname = 'Stepper motor position / speed'
+    desc = 'Absolute position and movement speed from step/dir.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['stepper_motor']
+    channels = (
+        {'id': 'step', 'name': 'Step', 'desc': 'Step pulse'},
+        {'id': 'dir', 'name': 'Direction', 'desc': 'Direction select'},
+    )
+    options = (
+        {'id': 'unit', 'desc': 'Unit', 'default': 'steps',
+         'values': ('steps', 'mm')},
+        {'id': 'steps_per_mm', 'desc': 'Steps per mm', 'default': 100.0},
+    )
+    annotations = (
+        ('speed', 'Speed'),
+        ('position', 'Position')
+    )
+    annotation_rows = (
+        ('speed', 'Speed', (0,)),
+        ('position', 'Position', (1,)),
+    )
+
+    def __init__(self):
+        self.oldstep = None
+        self.ss_prev_step = None
+        self.pos = 0
+        self.prev_speed = None
+        self.prev_pos = None
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+        if self.options['unit'] == 'steps':
+            self.scale = 1
+            self.format = '%0.0f'
+            self.unit = 'steps'
+        else:
+            self.scale = self.options['steps_per_mm']
+            self.format = '%0.2f'
+            self.unit = 'mm'
+
+    def step(self, ss, direction):
+        if self.ss_prev_step is not None:
+            delta = ss - self.ss_prev_step
+            speed = self.samplerate / delta / self.scale
+            speed_txt = self.format % speed
+            pos_txt = self.format % (self.pos / self.scale)
+            self.put(self.ss_prev_step, ss, self.out_ann,
+                [0, [speed_txt + ' ' + self.unit + '/s', speed_txt]])
+            self.put(self.ss_prev_step, ss, self.out_ann,
+                [1, [pos_txt + ' ' + self.unit, pos_txt]])
+
+        self.pos += (1 if direction else -1)
+        self.ss_prev_step = ss
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+
+        for (self.samplenum, (step, direction)) in data:
+            if step == 1 and self.oldstep == 0:
+                self.step(self.samplenum, direction)
+            self.oldstep = step
diff --git a/decoders/dcf77/__init__.py b/decoders/swd/__init__.py
similarity index 62%
copy from decoders/dcf77/__init__.py
copy to decoders/swd/__init__.py
index 04805c2..3a65143 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/swd/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Angus Gratton <gus at projectgus.com>
 ##
 ## 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
@@ -19,12 +19,17 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+This PD decodes the ARM SWD (version 1) protocol, as described in the
+"ARM Debug Interface v5.2" Architecture Specification.
 
 Details:
-http://en.wikipedia.org/wiki/DCF77
-'''
+http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0031c/index.html
+(Registration required)
 
-from .pd import *
+Not supported:
+ * Turnaround periods other than the default 1, as set in DLCR.TURNROUND
+   (should be trivial to add)
+ * SWD protocol version 2 (multi-drop support, etc.)
+'''
 
+from .pd import Decoder
diff --git a/decoders/swd/pd.py b/decoders/swd/pd.py
new file mode 100644
index 0000000..3414c35
--- /dev/null
+++ b/decoders/swd/pd.py
@@ -0,0 +1,349 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Angus Gratton <gus at projectgus.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import re
+
+'''
+OUTPUT_PYTHON format:
+
+Packet:
+[<ptype>, <pdata>]
+
+<ptype>:
+ - 'AP_READ' (AP read)
+ - 'DP_READ' (DP read)
+ - 'AP_WRITE' (AP write)
+ - 'DP_WRITE' (DP write)
+ - 'LINE_RESET' (line reset sequence)
+
+<pdata>:
+  - tuple of address, ack state, data for the given sequence
+'''
+
+swd_states = [
+    'IDLE', # Idle/unknown
+    'REQUEST', # Request phase (first 8 bits)
+    'ACK', # Ack phase (next 3 bits)
+    'READ', # Reading phase (next 32 bits for reads)
+    'WRITE', # Writing phase (next 32 bits for write)
+    'DPARITY', # Data parity phase
+]
+
+# Regexes for matching SWD data out of bitstring ('1' / '0' characters) format
+RE_SWDSWITCH = re.compile(bin(0xE79E)[:1:-1] + '$')
+RE_SWDREQ = re.compile(r'1(?P<apdp>.)(?P<rw>.)(?P<addr>..)(?P<parity>.)01$')
+RE_IDLE = re.compile('0' * 50 + '$')
+
+# Sample edges
+RISING = 1
+FALLING = 0
+
+ADDR_DP_SELECT = 0x8
+ADDR_DP_CTRLSTAT = 0x4
+
+BIT_SELECT_CTRLSEL = 1
+BIT_CTRLSTAT_ORUNDETECT = 1
+
+ANNOTATIONS = ['reset', 'enable', 'read', 'write', 'ack', 'data', 'parity']
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'swd'
+    name = 'SWD'
+    longname = 'Serial Wire Debug'
+    desc = 'Two-wire protocol for debug access to ARM CPUs.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['swd']
+    channels = (
+        {'id': 'swclk', 'name': 'SWCLK', 'desc': 'Master clock'},
+        {'id': 'swdio', 'name': 'SWDIO', 'desc': 'Data input/output'},
+    )
+    options = (
+        {'id': 'strict_start',
+         'desc': 'Wait for a line reset before starting to decode',
+         'default': 'no', 'values': ('yes', 'no')},
+    )
+    annotations = (
+        ('reset', 'RESET'),
+        ('enable', 'ENABLE'),
+        ('read', 'READ'),
+        ('write', 'WRITE'),
+        ('ack', 'ACK'),
+        ('data', 'DATA'),
+        ('parity', 'PARITY'),
+    )
+
+    def __init__(self):
+        # SWD data/clock state
+        self.state = 'UNKNOWN'
+        self.oldclk = -1
+        self.sample_edge = RISING
+        self.ack = None # Ack state of the current phase
+        self.ss_req = 0 # Start sample of current req
+        self.turnaround = 0 # Number of turnaround edges to ignore before continuing
+        self.bits = '' # Bits from SWDIO are accumulated here, matched against expected sequences
+        self.samplenums = [] # Sample numbers that correspond to the samples in self.bits
+        self.linereset_count = 0
+
+        # SWD debug port state
+        self.data = None
+        self.addr = None
+        self.rw = None # Are we inside an SWD read or a write?
+        self.ctrlsel = 0 # 'ctrlsel' is bit 0 in the SELECT register.
+        self.orundetect = 0 # 'orundetect' is bit 0 in the CTRLSTAT register.
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        if self.options['strict_start'] == 'no':
+            self.state = 'REQ' # No need to wait for a LINE RESET.
+
+    def putx(self, ann, length, data):
+        '''Output annotated data.'''
+        ann = ANNOTATIONS.index(ann)
+        try:
+            ss = self.samplenums[-length]
+        except IndexError:
+            ss = self.samplenums[0]
+        if self.state == 'REQ':
+            self.ss_req = ss
+        es = self.samplenum
+        self.put(ss, es, self.out_ann, [ann, [data]])
+
+    def putp(self, ptype, pdata):
+        self.put(self.ss_req, self.samplenum, self.out_python, [ptype, pdata])
+
+    def put_python_data(self):
+        '''Emit Python data item based on current SWD packet contents.'''
+        ptype = {
+            ('AP', 'R'): 'AP_READ',
+            ('AP', 'W'): 'AP_WRITE',
+            ('DP', 'R'): 'DP_READ',
+            ('DP', 'W'): 'DP_WRITE',
+        }[(self.apdp, self.rw)]
+        self.putp(ptype, (self.addr, self.data, self.ack))
+
+    def decode(self, ss, es, data):
+        for (self.samplenum, (clk, dio)) in data:
+            if clk == self.oldclk:
+                continue # Not a clock edge.
+            self.oldclk = clk
+
+            # Count rising edges with DIO held high,
+            # as a line reset (50+ high edges) can happen from any state.
+            if clk == RISING:
+                if dio == 1:
+                    self.linereset_count += 1
+                else:
+                    if self.linereset_count >= 50:
+                        self.putx('reset', self.linereset_count, 'LINERESET')
+                        self.putp('LINE_RESET', None)
+                        self.reset_state()
+                    self.linereset_count = 0
+
+            # Otherwise, we only care about either rising or falling edges
+            # (depending on sample_edge, set according to current state).
+            if clk != self.sample_edge:
+                continue
+
+            # Turnaround bits get skipped.
+            if self.turnaround > 0:
+                self.turnaround -= 1
+                continue
+
+            self.bits += str(dio)
+            self.samplenums.append(self.samplenum)
+            {
+                'UNKNOWN': self.handle_unknown_edge,
+                'REQ': self.handle_req_edge,
+                'ACK': self.handle_ack_edge,
+                'DATA': self.handle_data_edge,
+                'DPARITY': self.handle_dparity_edge,
+            }[self.state]()
+
+    def next_state(self):
+        '''Step to the next SWD state, reset internal counters accordingly.'''
+        self.bits = ''
+        self.samplenums = []
+        self.linereset_count = 0
+        if self.state == 'UNKNOWN':
+            self.state = 'REQ'
+            self.sample_edge = RISING
+            self.turnaround = 0
+        elif self.state == 'REQ':
+            self.state = 'ACK'
+            self.sample_edge = FALLING
+            self.turnaround = 1
+        elif self.state == 'ACK':
+            self.state = 'DATA'
+            self.sample_edge = RISING if self.rw == 'W' else FALLING
+            self.turnaround = 0 if self.rw == 'R' else 2
+        elif self.state == 'DATA':
+            self.state = 'DPARITY'
+        elif self.state == 'DPARITY':
+            self.put_python_data()
+            self.state = 'REQ'
+            self.sample_edge = RISING
+            self.turnaround = 1 if self.rw == 'R' else 0
+
+    def reset_state(self):
+        '''Line reset (or equivalent), wait for a new pending SWD request.'''
+        if self.state != 'REQ': # Emit a Python data item.
+            self.put_python_data()
+        # Clear state.
+        self.bits = ''
+        self.samplenums = []
+        self.linereset_count = 0
+        self.turnaround = 0
+        self.sample_edge = RISING
+        self.data = ''
+        self.ack = None
+        self.state = 'REQ'
+
+    def handle_unknown_edge(self):
+        '''
+        Clock edge in the UNKNOWN state.
+        In the unknown state, clock edges get ignored until we see a line
+        reset (which is detected in the decode method, not here.)
+        '''
+        pass
+
+    def handle_req_edge(self):
+        '''Clock edge in the REQ state (waiting for SWD r/w request).'''
+        # Check for a JTAG->SWD enable sequence.
+        m = re.search(RE_SWDSWITCH, self.bits)
+        if m is not None:
+            self.putx('enable', 16, 'JTAG->SWD')
+            self.reset_state()
+            return
+
+        # Or a valid SWD Request packet.
+        m = re.search(RE_SWDREQ, self.bits)
+        if m is not None:
+            calc_parity = sum([int(x) for x in m.group('rw') + m.group('apdp') + m.group('addr')]) % 2
+            parity = '' if str(calc_parity) == m.group('parity') else 'E'
+            self.rw = 'R' if m.group('rw') == '1' else 'W'
+            self.apdp = 'AP' if m.group('apdp') == '1' else 'DP'
+            self.addr = int(m.group('addr')[::-1], 2) << 2
+            self.putx('read' if self.rw == 'R' else 'write', 8, self.get_address_description())
+            self.next_state()
+            return
+
+    def handle_ack_edge(self):
+        '''Clock edge in the ACK state (waiting for complete ACK sequence).'''
+        if len(self.bits) < 3:
+            return
+        if self.bits == '100':
+            self.putx('ack', 3, 'OK')
+            self.ack = 'OK'
+            self.next_state()
+        elif self.bits == '001':
+            self.putx('ack', 3, 'FAULT')
+            self.ack = 'FAULT'
+            if self.orundetect == 1:
+                self.next_state()
+            else:
+                self.reset_state()
+            self.turnaround = 1
+        elif self.bits == '010':
+            self.putx('ack', 3, 'WAIT')
+            self.ack = 'WAIT'
+            if self.orundetect == 1:
+                self.next_state()
+            else:
+                self.reset_state()
+            self.turnaround = 1
+        elif self.bits == '111':
+            self.putx('ack', 3, 'NOREPLY')
+            self.ack = 'NOREPLY'
+            self.reset_state()
+        else:
+            self.putx('ack', 3, 'ERROR')
+            self.ack = 'ERROR'
+            self.reset_state()
+
+    def handle_data_edge(self):
+        '''Clock edge in the DATA state (waiting for 32 bits to clock past).'''
+        if len(self.bits) < 32:
+            return
+        self.data = 0
+        self.dparity = 0
+        for x in range(32):
+            if self.bits[x] == '1':
+                self.data += (1 << x)
+                self.dparity += 1
+        self.dparity = self.dparity % 2
+
+        self.putx('data', 32, '0x%08x' % self.data)
+        self.next_state()
+
+    def handle_dparity_edge(self):
+        '''Clock edge in the DPARITY state (clocking in parity bit).'''
+        if str(self.dparity) != self.bits:
+            self.putx('parity', 1, str(self.dparity) + self.bits) # PARITY ERROR
+        elif self.rw == 'W':
+            self.handle_completed_write()
+        self.next_state()
+
+    def handle_completed_write(self):
+        '''
+        Update internal state of the debug port based on a completed
+        write operation.
+        '''
+        if self.apdp != 'DP':
+            return
+        elif self.addr == ADDR_DP_SELECT:
+            self.ctrlsel = self.data & BIT_SELECT_CTRLSEL
+        elif self.addr == ADDR_DP_CTRLSTAT and self.ctrlsel == 0:
+            self.orundetect = self.data & BIT_CTRLSTAT_ORUNDETECT
+
+    def get_address_description(self):
+        '''
+        Return a human-readable description of the currently selected address,
+        for annotated results.
+        '''
+        if self.apdp == 'DP':
+            if self.rw == 'R':
+                # Tables 2-4 & 2-5 in ADIv5.2 spec ARM document IHI 0031C
+                return {
+                    0: 'IDCODE',
+                    0x4: 'R CTRL/STAT' if self.ctrlsel == 0 else 'R DLCR',
+                    0x8: 'RESEND',
+                    0xC: 'RDBUFF'
+                }[self.addr]
+            elif self.rw == 'W':
+                # Tables 2-4 & 2-5 in ADIv5.2 spec ARM document IHI 0031C
+                return {
+                    0: 'W ABORT',
+                    0x4: 'W CTRL/STAT' if self.ctrlsel == 0 else 'W DLCR',
+                    0x8: 'W SELECT',
+                    0xC: 'W RESERVED'
+                }[self.addr]
+        elif self.apdp == 'AP':
+            if self.rw == 'R':
+                return 'R AP%x' % self.addr
+            elif self.rw == 'W':
+                return 'W AP%x' % self.addr
+
+        # Any legitimate operations shouldn't fall through to here, probably
+        # a decoder bug.
+        return '? %s%s%x' % (self.rw, self.apdp, self.addr)
diff --git a/decoders/ir_nec/__init__.py b/decoders/t55xx/__init__.py
similarity index 79%
copy from decoders/ir_nec/__init__.py
copy to decoders/t55xx/__init__.py
index 84bf428..8f0f8a4 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/t55xx/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2015 Benjamin Larsson <benjamin at southpole.se>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+T55xx is a 100-150kHz RFID protocol according to the Atmel e555x
+downlink/write protocol (pulse interval coding).
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/t55xx/pd.py b/decoders/t55xx/pd.py
new file mode 100644
index 0000000..57838f0
--- /dev/null
+++ b/decoders/t55xx/pd.py
@@ -0,0 +1,331 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Benjamin Larsson <benjamin at southpole.se>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 't55xx'
+    name = 'T55xx'
+    longname = 'RFID T55xx'
+    desc = 'T55xx 100-150kHz RFID protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['t55xx']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    options = (
+        {'id': 'coilfreq', 'desc': 'Coil frequency', 'default': 125000},
+        {'id': 'start_gap', 'desc': 'Start gap min', 'default': 20},
+        {'id': 'w_gap', 'desc': 'Write gap min', 'default': 20},
+        {'id': 'w_one_min', 'desc': 'Write one min', 'default': 48},
+        {'id': 'w_one_max', 'desc': 'Write one max', 'default': 63},
+        {'id': 'w_zero_min', 'desc': 'Write zero min', 'default': 16},
+        {'id': 'w_zero_max', 'desc': 'Write zero max', 'default': 31},
+        {'id': 'em4100_decode', 'desc': 'EM4100 decode', 'default': 'on',
+            'values': ('on', 'off')},
+    )
+    annotations = (
+        ('bit_value', 'Bit value'),
+        ('start_gap', 'Start gap'),
+        ('write_gap', 'Write gap'),
+        ('write_mode_exit', 'Write mode exit'),
+        ('bit', 'Bit'),
+        ('opcode', 'Opcode'),
+        ('lock', 'Lock'),
+        ('data', 'Data'),
+        ('password', 'Password'),
+        ('address', 'Address'),
+        ('bitrate', 'Bitrate'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (0,)),
+        ('structure', 'Structure', (1, 2, 3, 4)),
+        ('fields', 'Fields', (5, 6, 7, 8, 9)),
+        ('decode', 'Decode', (10,)),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.oldpin = None
+        self.last_samplenum = None
+        self.lastlast_samplenum = None
+        self.state = 'START_GAP'
+        self.bits_pos = [[0 for col in range(3)] for row in range(70)]
+        self.br_string = ['RF/8', 'RF/16', 'RF/32', 'RF/40',
+                          'RF/50', 'RF/64', 'RF/100', 'RF/128']
+        self.mod_str1 = ['Direct', 'Manchester', 'Biphase', 'Reserved']
+        self.mod_str2 = ['Direct', 'PSK1', 'PSK2', 'PSK3', 'FSK1', 'FSK2',
+                         'FSK1a', 'FSK2a']
+        self.pskcf_str = ['RF/2', 'RF/4', 'RF/8', 'Reserved']
+        self.em4100_decode1_partial = 0
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+        self.field_clock = self.samplerate / self.options['coilfreq']
+        self.wzmax = self.options['w_zero_max'] * self.field_clock
+        self.wzmin = self.options['w_zero_min'] * self.field_clock
+        self.womax = self.options['w_one_max'] * self.field_clock
+        self.womin = self.options['w_one_min'] * self.field_clock
+        self.startgap = self.options['start_gap'] * self.field_clock
+        self.writegap = self.options['w_gap'] * self.field_clock
+        self.nogap = 64 * self.field_clock
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def decode_config(self, idx):
+        safer_key = self.bits_pos[idx][0]<<3 | self.bits_pos[idx+1][0]<<2 | \
+                    self.bits_pos[idx+2][0]<<1 | self.bits_pos[idx+3][0]
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+3][2], self.out_ann,
+                 [10, ['Safer Key' + ': %X' % safer_key,'%X' % safer_key]])
+        bitrate = self.bits_pos[idx+11][0]<<2 | self.bits_pos[idx+12][0]<<1 | \
+                  self.bits_pos[idx+13][0]
+        self.put(self.bits_pos[idx+11][1], self.bits_pos[idx+13][2],
+                 self.out_ann, [10, ['Data Bit Rate: ' + \
+                 self.br_string[bitrate], self.br_string[bitrate]]])
+        modulation1 = self.bits_pos[idx+15][0]<<1 | self.bits_pos[idx+16][0]
+        modulation2 = self.bits_pos[idx+17][0]<<2 | \
+                      self.bits_pos[idx+18][0]<<1 | self.bits_pos[idx+19][0]
+        if modulation1 == 0:
+            mod_string = self.mod_str2[modulation2]
+        else:
+            mod_string = self.mod_str1[modulation1]
+        self.put(self.bits_pos[idx+15][1], self.bits_pos[idx+19][2],
+                 self.out_ann, [10, ['Modulation: ' + mod_string, mod_string]])
+        psk_cf = self.bits_pos[idx+20][0]<<1 | self.bits_pos[idx+21][0]
+        self.put(self.bits_pos[idx+20][1], self.bits_pos[idx+21][2],
+                 self.out_ann, [10, ['PSK-CF: ' + self.pskcf_str[psk_cf],
+                 self.pskcf_str[psk_cf]]])
+        self.put(self.bits_pos[idx+22][1], self.bits_pos[idx+22][2],
+                 self.out_ann, [10, ['AOR' + ': %d' % \
+                 (self.bits_pos[idx+22][0]),'%d' % (self.bits_pos[idx+22][0])]])
+        maxblock = self.bits_pos[idx+24][0]<<2 | self.bits_pos[idx+25][0]<<1 | \
+                   self.bits_pos[idx+26][0]
+        self.put(self.bits_pos[idx+24][1], self.bits_pos[idx+26][2],
+                 self.out_ann, [10, ['Max-Block' + ': %d' % maxblock,
+                 '%d' % maxblock]])
+        self.put(self.bits_pos[idx+27][1], self.bits_pos[idx+27][2],
+                 self.out_ann, [10, ['PWD' + ': %d' % \
+                 (self.bits_pos[idx+27][0]),'%d' % (self.bits_pos[idx+27][0])]])
+        self.put(self.bits_pos[idx+28][1], self.bits_pos[idx+28][2],
+                 self.out_ann, [10, ['ST-sequence terminator' + ': %d' % \
+                 (self.bits_pos[idx+28][0]),'%d' % (self.bits_pos[idx+28][0])]])
+        self.put(self.bits_pos[idx+31][1], self.bits_pos[idx+31][2],
+                 self.out_ann, [10, ['POR delay' + ': %d' % \
+                 (self.bits_pos[idx+31][0]),'%d' % (self.bits_pos[idx+31][0])]])
+
+    def put4bits(self, idx):
+        bits = self.bits_pos[idx][0]<<3 | self.bits_pos[idx+1][0]<<2 | \
+               self.bits_pos[idx+2][0]<<1 | self.bits_pos[idx+3][0]
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+3][2], self.out_ann,
+                 [10, ['%X' % bits]])
+
+    def em4100_decode1(self, idx):
+        self.put(self.bits_pos[idx][1], self.bits_pos[idx+8][2], self.out_ann,
+                 [10, ['EM4100 header', 'EM header', 'Header', 'H']])
+        self.put4bits(idx+9)
+        self.put4bits(idx+14)
+        self.put4bits(idx+19)
+        self.put4bits(idx+24)
+        self.em4100_decode1_partial = self.bits_pos[idx+29][0]<<3 | \
+            self.bits_pos[idx+30][0]<<2 | self.bits_pos[idx+31][0]<<1
+        self.put(self.bits_pos[idx+29][1], self.bits_pos[idx+31][2],
+                 self.out_ann, [10, ['Partial nibble']])
+
+    def em4100_decode2(self, idx):
+        if self.em4100_decode1_partial != 0:
+            bits = self.em4100_decode1_partial + self.bits_pos[idx][0]
+            self.put(self.bits_pos[idx][1], self.bits_pos[idx][2],
+                     self.out_ann, [10, ['%X' % bits]])
+            self.em4100_decode1_partial = 0
+        else:
+            self.put(self.bits_pos[idx][1], self.bits_pos[idx][2],
+                     self.out_ann, [10, ['Partial nibble']])
+
+        self.put4bits(idx+2)
+        self.put4bits(idx+7)
+        self.put4bits(idx+12)
+        self.put4bits(idx+17)
+        self.put4bits(idx+22)
+        self.put(self.bits_pos[idx+27][1], self.bits_pos[idx+31][2],
+                 self.out_ann, [10, ['EM4100 trailer']])
+
+    def get_32_bits(self, idx):
+        retval = 0
+        for i in range(0, 32):
+            retval <<= 1
+            retval |= self.bits_pos[i+idx][0]
+        return retval
+
+    def get_3_bits(self, idx):
+        retval = self.bits_pos[idx][0]<<2 | self.bits_pos[idx+1][0]<<1 | \
+                 self.bits_pos[idx+2][0]
+        return retval
+
+    def put_fields(self):
+        if (self.bit_nr == 70):
+            self.put(self.bits_pos[0][1], self.bits_pos[1][2], self.out_ann,
+                     [5, ['Opcode' + ': %d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0]), '%d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0])]])
+            password = self.get_32_bits(2)
+            self.put(self.bits_pos[2][1], self.bits_pos[33][2], self.out_ann,
+                     [8, ['Password' + ': %X' % password, '%X' % password]])
+            self.put(self.bits_pos[34][1], self.bits_pos[34][2], self.out_ann,
+                     [6, ['Lock' + ': %X' % self.bits_pos[34][0],
+                     '%X' % self.bits_pos[34][0]]])
+            data = self.get_32_bits(35)
+            self.put(self.bits_pos[35][1], self.bits_pos[66][2], self.out_ann,
+                     [7, ['Data' + ': %X' % data, '%X' % data]])
+            addr = self.get_3_bits(67)
+            self.put(self.bits_pos[67][1], self.bits_pos[69][2], self.out_ann,
+                     [9, ['Addr' + ': %X' % addr, '%X' % addr]])
+            if addr == 0:
+                self.decode_config(35)
+            if addr == 7:
+                self.put(self.bits_pos[35][1], self.bits_pos[66][2],
+                         self.out_ann, [10, ['Password' + ': %X' % data,
+                         '%X' % data]])
+            # If we are programming EM4100 data we can decode it halfway.
+            if addr == 1 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode1(35)
+            if addr == 2 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode2(35)
+
+        if (self.bit_nr == 38):
+            self.put(self.bits_pos[0][1], self.bits_pos[1][2], self.out_ann,
+                     [5, ['Opcode' + ': %d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0]), '%d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0])]])
+            self.put(self.bits_pos[2][1], self.bits_pos[2][2], self.out_ann,
+                     [6, ['Lock' + ': %X' % self.bits_pos[2][0],
+                     '%X' % self.bits_pos[2][0]]])
+            data = self.get_32_bits(3)
+            self.put(self.bits_pos[3][1], self.bits_pos[34][2], self.out_ann,
+                     [7, ['Data' + ': %X' % data, '%X' % data]])
+            addr = self.get_3_bits(35)
+            self.put(self.bits_pos[35][1], self.bits_pos[37][2], self.out_ann,
+                     [9, ['Addr' + ': %X' % addr, '%X' % addr]])
+            if addr == 0:
+                self.decode_config(3)
+            if addr == 7:
+                self.put(self.bits_pos[3][1], self.bits_pos[34][2],
+                         self.out_ann, [10, ['Password' + ': %X' % data,
+                         '%X' % data]])
+            # If we are programming EM4100 data we can decode it halfway.
+            if addr == 1 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode1(3)
+            if addr == 2 and self.options['em4100_decode'] == 'on':
+                self.em4100_decode2(3)
+
+        if (self.bit_nr == 2):
+            self.put(self.bits_pos[0][1], self.bits_pos[1][2], self.out_ann,
+                     [5, ['Opcode' + ': %d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0]), '%d%d' % (self.bits_pos[0][0],
+                     self.bits_pos[1][0])]])
+        self.bit_nr = 0
+
+    def add_bits_pos(self, bit, bit_start, bit_end):
+        if self.bit_nr < 70:
+            self.bits_pos[self.bit_nr][0] = bit
+            self.bits_pos[self.bit_nr][1] = bit_start
+            self.bits_pos[self.bit_nr][2] = bit_end
+            self.bit_nr += 1
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, (pin,)) in data:
+            # Ignore identical samples early on (for performance reasons).
+            if self.oldpin == pin:
+                continue
+
+            if self.oldpin is None:
+                self.oldpin = pin
+                self.last_samplenum = self.samplenum
+                self.lastlast_samplenum = self.samplenum
+                self.last_edge = self.samplenum
+                self.oldpl = 0
+                self.oldpp = 0
+                self.oldsamplenum = 0
+                self.last_bit_pos = 0
+
+                self.old_gap_start = 0
+                self.old_gap_end = 0
+                self.gap_detected = 0
+                self.bit_nr = 0
+                continue
+
+            if self.oldpin != pin:
+                pl = self.samplenum - self.oldsamplenum
+                pp = pin
+                samples = self.samplenum - self.last_samplenum
+
+                if self.state == 'WRITE_GAP':
+                    if pl > self.writegap:
+                        self.gap_detected = 1
+                        self.put(self.last_samplenum, self.samplenum,
+                                 self.out_ann, [2, ['Write gap']])
+                    if (self.last_samplenum-self.old_gap_end) > self.nogap:
+                        self.gap_detected = 0
+                        self.state = 'START_GAP'
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [3, ['Write mode exit']])
+                        self.put_fields()
+
+                if self.state == 'START_GAP':
+                    if pl > self.startgap:
+                        self.gap_detected = 1
+                        self.put(self.last_samplenum, self.samplenum,
+                                 self.out_ann, [1, ['Start gap']])
+                        self.state = 'WRITE_GAP'
+
+                if self.gap_detected == 1:
+                    self.gap_detected = 0
+                    if (self.last_samplenum - self.old_gap_end) > self.wzmin \
+                            and (self.last_samplenum - self.old_gap_end) < self.wzmax:
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [0, ['0']])
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [4, ['Bit']])
+                        self.add_bits_pos(0, self.old_gap_end,
+                                          self.last_samplenum)
+                    if (self.last_samplenum - self.old_gap_end) > self.womin \
+                            and (self.last_samplenum - self.old_gap_end) < self.womax:
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [0, ['1']])
+                        self.put(self.old_gap_end, self.last_samplenum,
+                                 self.out_ann, [4, ['Bit']])
+                        self.add_bits_pos(1, self.old_gap_end, self.last_samplenum)
+
+                    self.old_gap_start = self.last_samplenum
+                    self.old_gap_end = self.samplenum
+
+                self.oldpl = pl
+                self.oldpp = pp
+                self.oldsamplenum = self.samplenum
+                self.last_samplenum = self.samplenum
+                self.oldpin = pin
diff --git a/decoders/ir_nec/__init__.py b/decoders/tca6408a/__init__.py
similarity index 79%
copy from decoders/ir_nec/__init__.py
copy to decoders/tca6408a/__init__.py
index 84bf428..f679674 100644
--- a/decoders/ir_nec/__init__.py
+++ b/decoders/tca6408a/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2014 Gump Yang <gump.yang at gmail.com>
+## Copyright (C) 2014 alberink <alberink at stampfini.org>
 ##
 ## 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
@@ -19,8 +19,8 @@
 ##
 
 '''
-NEC is a pulse-distance based infrared remote control protocol.
+This decoder stacks on top of the 'i2c' PD and decodes the Texas Instruments
+TCA6408A 8-bit I²C I/O expander protocol.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/tca6408a/pd.py b/decoders/tca6408a/pd.py
new file mode 100644
index 0000000..a794547
--- /dev/null
+++ b/decoders/tca6408a/pd.py
@@ -0,0 +1,129 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2013 Matt Ranostay <mranostay at gmail.com>
+## Copyright (C) 2014 alberink <alberink at stampfini.org>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'tca6408a'
+    name = 'TI TCA6408A'
+    longname = 'Texas Instruments TCA6408A'
+    desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.'
+    license = 'gplv2+'
+    inputs = ['i2c']
+    outputs = ['tca6408a']
+    annotations = (
+        ('register', 'Register type'),
+        ('value', 'Register value'),
+        ('warnings', 'Warning messages'),
+    )
+    annotation_rows = (
+        ('regs', 'Registers', (0, 1)),
+        ('warnings', 'Warnings', (2,)),
+    )
+
+    def __init__(self):
+        self.state = 'IDLE'
+        self.chip = -1
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def putx(self, data):
+        self.put(self.ss, self.es, self.out_ann, data)
+
+    def handle_reg_0x00(self, b):
+        self.putx([1, ['State of inputs: %02X' % b]])
+
+    def handle_reg_0x01(self, b):
+        self.putx([1, ['Outputs set: %02X' % b ]])
+
+    def handle_reg_0x02(self, b):
+        self.putx([1, ['Polarity inverted: %02X' % b]])
+
+    def handle_reg_0x03(self, b):
+        self.putx([1, ['Configuration: %02X' % b]])
+
+    def handle_write_reg(self, b):
+        if b == 0:
+            self.putx([0, ['Input port', 'In', 'I']])
+        elif b == 1:
+            self.putx([0, ['Output port', 'Out', 'O']])
+        elif b == 2:
+            self.putx([0, ['Polarity inversion register', 'Pol', 'P']])
+        elif b == 3:
+            self.putx([0, ['Configuration register', 'Conf', 'C']])
+
+    def check_correct_chip(self, addr):
+        if addr not in (0x20, 0x21):
+            self.putx([2, ['Warning: I²C slave 0x%02X not a TCA6408A '
+                           'compatible chip.' % addr]])
+            self.state = 'IDLE'
+
+    def decode(self, ss, es, data):
+        cmd, databyte = data
+
+        # Store the start/end samples of this I²C packet.
+        self.ss, self.es = ss, es
+
+        # State machine.
+        if self.state == 'IDLE':
+            # Wait for an I²C START condition.
+            if cmd != 'START':
+                return
+            self.state = 'GET SLAVE ADDR'
+        elif self.state == 'GET SLAVE ADDR':
+            self.chip = databyte  
+            self.state = 'GET REG ADDR'
+        elif self.state == 'GET REG ADDR':
+            # Wait for a data write (master selects the slave register).
+            if cmd in ('ADDRESS READ', 'ADDRESS WRITE'):
+                self.check_correct_chip(databyte)
+            if cmd != 'DATA WRITE':
+                return
+            self.reg = databyte
+            self.handle_write_reg(self.reg)
+            self.state = 'WRITE IO REGS'
+        elif self.state == 'WRITE IO REGS':
+            # If we see a Repeated Start here, the master wants to read.
+            if cmd == 'START REPEAT':
+                self.state = 'READ IO REGS'
+                return
+            # Otherwise: Get data bytes until a STOP condition occurs.
+            if cmd == 'DATA WRITE':
+                handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)
+                handle_reg(databyte)
+            elif cmd == 'STOP':
+                self.state = 'IDLE'
+                self.chip = -1
+        elif self.state == 'READ IO REGS':
+            # Wait for an address read operation.
+            if cmd == 'ADDRESS READ':
+                self.state = 'READ IO REGS2'
+                self.chip = databyte
+                return
+        elif self.state == 'READ IO REGS2':
+            if cmd == 'DATA READ':
+                handle_reg = getattr(self, 'handle_reg_0x%02x' % self.reg)
+                handle_reg(databyte)
+            elif cmd == 'STOP':
+                self.state = 'IDLE'
diff --git a/decoders/tlc5620/__init__.py b/decoders/timing/__init__.py
similarity index 86%
copy from decoders/tlc5620/__init__.py
copy to decoders/timing/__init__.py
index c615760..ee31509 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/timing/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2014 Torsten Duwe <duwe at suse.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
@@ -19,8 +19,7 @@
 ##
 
 '''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
+Timing decoder, find the time between edges.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/timing/pd.py b/decoders/timing/pd.py
new file mode 100644
index 0000000..98677b9
--- /dev/null
+++ b/decoders/timing/pd.py
@@ -0,0 +1,123 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2014 Torsten Duwe <duwe at suse.de>
+## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin at savoirfairelinux.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+from collections import deque
+
+class SamplerateError(Exception):
+    pass
+
+def normalize_time(t):
+    if t >= 1.0:
+        return '%.3f s  (%.3f Hz)' % (t, (1/t))
+    elif t >= 0.001:
+        if 1/t/1000 < 1:
+            return '%.3f ms (%.3f Hz)' % (t * 1000.0, (1/t))
+        else:
+            return '%.3f ms (%.3f kHz)' % (t * 1000.0, (1/t)/1000)
+    elif t >= 0.000001:
+        if 1/t/1000/1000 < 1:
+            return '%.3f μs (%.3f kHz)' % (t * 1000.0 * 1000.0, (1/t)/1000)
+        else:
+            return '%.3f μs (%.3f MHz)' % (t * 1000.0 * 1000.0, (1/t)/1000/1000)
+    elif t >= 0.000000001:
+        if 1/t/1000/1000/1000:
+            return '%.3f ns (%.3f MHz)' % (t * 1000.0 * 1000.0 * 1000.0, (1/t)/1000/1000)
+        else:
+            return '%.3f ns (%.3f GHz)' % (t * 1000.0 * 1000.0 * 1000.0, (1/t)/1000/1000/1000)
+    else:
+        return '%f' % t
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'timing'
+    name = 'Timing'
+    longname = 'Timing calculation with frequency and averaging'
+    desc = 'Calculate time between edges.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['timing']
+    channels = (
+        {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
+    )
+    annotations = (
+        ('time', 'Time'),
+        ('average', 'Average'),
+    )
+    annotation_rows = (
+        ('time', 'Time', (0,)),
+        ('average', 'Average', (1,)),
+    )
+    options = (
+        { 'id': 'avg_period', 'desc': 'Averaging period', 'default': 100 },
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.oldpin = None
+        self.last_samplenum = None
+        self.last_n = deque()
+        self.chunks = 0
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+
+    def start(self):
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+
+        for (self.samplenum, (pin,)) in data:
+            if self.oldpin is None:
+                self.oldpin = pin
+                self.last_samplenum = self.samplenum
+                continue
+
+            if self.oldpin != pin:
+                samples = self.samplenum - self.last_samplenum
+                t = samples / self.samplerate
+                self.chunks += 1
+
+                # Don't insert the first chunk into the averaging as it is
+                # not complete probably.
+                if self.last_samplenum is None or self.chunks < 2:
+                    # Report the timing normalized.
+                    self.put(self.last_samplenum, self.samplenum, self.out_ann,
+                             [0, [normalize_time(t)]])
+                else:
+                    if t > 0:
+                        self.last_n.append(t)
+
+                    if len(self.last_n) > self.options['avg_period']:
+                        self.last_n.popleft()
+
+                    # Report the timing normalized.
+                    self.put(self.last_samplenum, self.samplenum, self.out_ann,
+                             [0, [normalize_time(t)]])
+                    self.put(self.last_samplenum, self.samplenum, self.out_ann,
+                             [1, [normalize_time(sum(self.last_n) / len(self.last_n))]])
+
+                # Store data for next round.
+                self.last_samplenum = self.samplenum
+                self.oldpin = pin
diff --git a/decoders/tlc5620/__init__.py b/decoders/tlc5620/__init__.py
index c615760..cb95385 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/tlc5620/__init__.py
@@ -22,5 +22,4 @@
 The Texas Instruments TLC5620 is an 8-bit quad DAC.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/tlc5620/pd.py b/decoders/tlc5620/pd.py
index f8c90d9..317e4ed 100644
--- a/decoders/tlc5620/pd.py
+++ b/decoders/tlc5620/pd.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2012-2015 Uwe Hermann <uwe at hermann-uwe.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
@@ -44,68 +44,147 @@ class Decoder(srd.Decoder):
         {'id': 'load', 'name': 'LOAD', 'desc': 'Serial interface load control'},
         {'id': 'ldac', 'name': 'LDAC', 'desc': 'Load DAC'},
     )
+    options = (
+        {'id': 'vref_a', 'desc': 'Reference voltage DACA (V)', 'default': 3.3},
+        {'id': 'vref_b', 'desc': 'Reference voltage DACB (V)', 'default': 3.3},
+        {'id': 'vref_c', 'desc': 'Reference voltage DACC (V)', 'default': 3.3},
+        {'id': 'vref_d', 'desc': 'Reference voltage DACD (V)', 'default': 3.3},
+    )
     annotations = (
         ('dac-select', 'DAC select'),
         ('gain', 'Gain'),
         ('value', 'DAC value'),
         ('data-latch', 'Data latch point'),
         ('ldac-fall', 'LDAC falling edge'),
+        ('bit', 'Bit'),
+        ('reg-write', 'Register write'),
+        ('voltage-update', 'Voltage update'),
+        ('voltage-update-all', 'Voltage update (all DACs)'),
+        ('invalid-cmd', 'Invalid command'),
+    )
+    annotation_rows = (
+        ('bits', 'Bits', (5,)),
+        ('fields', 'Fields', (0, 1, 2)),
+        ('registers', 'Registers', (6, 7)),
+        ('voltage-updates', 'Voltage updates', (8,)),
+        ('events', 'Events', (3, 4)),
+        ('errors', 'Errors', (9,)),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.oldpins = self.oldclk = self.oldload = self.oldldac = None
-        self.datapin = None
         self.bits = []
+        self.ss_dac_first = None
         self.ss_dac = self.es_dac = 0
         self.ss_gain = self.es_gain = 0
         self.ss_value = self.es_value = 0
         self.dac_select = self.gain = self.dac_value = None
+        self.dacval = {'A': '?', 'B': '?', 'C': '?', 'D': '?'}
+        self.gains = {'A': '?', 'B': '?', 'C': '?', 'D': '?'}
 
     def start(self):
         self.out_ann = self.register(srd.OUTPUT_ANN)
 
     def handle_11bits(self):
-        s = "".join(str(i) for i in self.bits[:2])
+        # Only look at the last 11 bits, the rest is ignored by the TLC5620.
+        if len(self.bits) > 11:
+            self.bits = self.bits[-11:]
+
+        # If there are less than 11 bits, something is probably wrong.
+        if len(self.bits) < 11:
+            ss, es = self.samplenum, self.samplenum
+            if len(self.bits) >= 2:
+                ss = self.bits[0][1]
+                es = self.bits[-1][1] + (self.bits[1][1] - self.bits[0][1])
+            self.put(ss, es, self.out_ann, [9, ['Command too short']])
+            self.bits = []
+            return False
+
+        self.ss_dac = self.bits[0][1]
+        self.es_dac = self.ss_gain = self.bits[2][1]
+        self.es_gain = self.ss_value = self.bits[3][1]
+        self.clock_width = self.es_gain - self.ss_gain
+        self.es_value = self.bits[10][1] + self.clock_width # Guessed.
+
+        if self.ss_dac_first is None:
+            self.ss_dac_first = self.ss_dac
+
+        s = ''.join(str(i[0]) for i in self.bits[:2])
         self.dac_select = s = dacs[int(s, 2)]
         self.put(self.ss_dac, self.es_dac, self.out_ann,
                  [0, ['DAC select: %s' % s, 'DAC sel: %s' % s,
                       'DAC: %s' % s, 'D: %s' % s, s, s[3]]])
 
-        self.gain = g = 1 + self.bits[2]
+        self.gain = g = 1 + self.bits[2][0]
         self.put(self.ss_gain, self.es_gain, self.out_ann,
                  [1, ['Gain: x%d' % g, 'G: x%d' % g, 'x%d' % g]])
 
-        s = "".join(str(i) for i in self.bits[3:])
+        s = ''.join(str(i[0]) for i in self.bits[3:])
         self.dac_value = v = int(s, 2)
         self.put(self.ss_value, self.es_value, self.out_ann,
                  [2, ['DAC value: %d' % v, 'Value: %d' % v, 'Val: %d' % v,
                       'V: %d' % v, '%d' % v]])
 
+        # Emit an annotation for each bit.
+        for i in range(1, 11):
+            self.put(self.bits[i - 1][1], self.bits[i][1], self.out_ann,
+                     [5, [str(self.bits[i - 1][0])]])
+        self.put(self.bits[10][1], self.bits[10][1] + self.clock_width,
+                 self.out_ann, [5, [str(self.bits[10][0])]])
+
+        self.bits = []
+
+        return True
+
     def handle_falling_edge_load(self):
+        if not self.handle_11bits():
+            return
         s, v, g = self.dac_select, self.dac_value, self.gain
         self.put(self.samplenum, self.samplenum, self.out_ann,
-                 [3, ['Setting %s value to %d (x%d gain)' % (s, v, g),
-                      '%s=%d (x%d gain)' % (s, v, g)]])
+                 [3, ['Falling edge on LOAD', 'LOAD fall', 'F']])
+        vref = self.options['vref_%s' % self.dac_select[3].lower()]
+        v = '%.2fV' % (vref * (v / 256) * self.gain)
+        if self.ldac == 0:
+            # If LDAC is low, the voltage is set immediately.
+            self.put(self.ss_dac, self.es_value, self.out_ann,
+                     [7, ['Setting %s voltage to %s' % (s, v),
+                          '%s=%s' % (s, v)]])
+        else:
+            # If LDAC is high, the voltage is not set immediately, but rather
+            # stored in a register. When LDAC goes low all four DAC voltages
+            # (DAC A/B/C/D) will be set at the same time.
+            self.put(self.ss_dac, self.es_value, self.out_ann,
+                     [6, ['Setting %s register value to %s' % \
+                          (s, v), '%s=%s' % (s, v)]])
+        # Save the last value the respective DAC was set to.
+        self.dacval[self.dac_select[-1]] = str(self.dac_value)
+        self.gains[self.dac_select[-1]] = self.gain
 
     def handle_falling_edge_ldac(self):
         self.put(self.samplenum, self.samplenum, self.out_ann,
-                 [4, ['Falling edge on LDAC pin', 'LDAC fall', 'LDAC']])
+                 [4, ['Falling edge on LDAC', 'LDAC fall', 'LDAC', 'L']])
+
+        # Don't emit any annotations if we didn't see any register writes.
+        if self.ss_dac_first is None:
+            return
+
+        # Calculate voltages based on Vref and the per-DAC gain.
+        dacval = {}
+        for key, val in self.dacval.items():
+            if val == '?':
+                dacval[key] = '?'
+            else:
+                vref = self.options['vref_%s' % key.lower()]
+                v = vref * (int(val) / 256) * self.gains[key]
+                dacval[key] = '%.2fV' % v
+
+        s = ''.join(['DAC%s=%s ' % (d, dacval[d]) for d in 'ABCD']).strip()
+        self.put(self.ss_dac_first, self.samplenum, self.out_ann,
+                 [8, ['Updating voltages: %s' % s, s, s.replace('DAC', '')]])
+        self.ss_dac_first = None
 
     def handle_new_dac_bit(self):
-        self.bits.append(self.datapin)
-
-        # Wait until we have read 11 bits, then parse them.
-        l, s = len(self.bits), self.samplenum
-        if l == 1:
-            self.ss_dac = s
-        elif l == 2:
-            self.es_dac = self.ss_gain = s
-        elif l == 3:
-            self.es_gain = self.ss_value = s
-        elif l == 11:
-            self.es_value = s
-            self.handle_11bits()
-            self.bits = []
+        self.bits.append([self.datapin, self.samplenum])
 
     def decode(self, ss, es, data):
         for (self.samplenum, pins) in data:
@@ -114,6 +193,7 @@ class Decoder(srd.Decoder):
             if self.oldpins == pins:
                 continue
             self.oldpins, (clk, self.datapin, load, ldac) = pins, pins
+            self.ldac = ldac
 
             # DATA is shifted in the DAC on the falling CLK edge (MSB-first).
             # A falling edge of LOAD will latch the data.
@@ -128,4 +208,3 @@ class Decoder(srd.Decoder):
             self.oldclk = clk
             self.oldload = load
             self.oldldac = ldac
-
diff --git a/decoders/uart/__init__.py b/decoders/uart/__init__.py
index f3c0693..efe0e52 100644
--- a/decoders/uart/__init__.py
+++ b/decoders/uart/__init__.py
@@ -38,5 +38,4 @@ it though, no matter whether the source was on TTL UART levels, or RS232,
 or others.
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/uart/pd.py b/decoders/uart/pd.py
index ae99874..0fa0e7f 100644
--- a/decoders/uart/pd.py
+++ b/decoders/uart/pd.py
@@ -19,6 +19,7 @@
 ##
 
 import sigrokdecode as srd
+from math import floor, ceil
 
 '''
 OUTPUT_PYTHON format:
@@ -28,9 +29,10 @@ Packet:
 
 This is the list of <ptype>s and their respective <pdata> values:
  - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
- - 'DATA': The data is the (integer) value of the UART data. Valid values
-   range from 0 to 512 (as the data can be up to 9 bits in size).
- - 'DATABITS': List of data bits and their ss/es numbers.
+ - 'DATA': This is always a tuple containing two items:
+   - 1st item: the (integer) value of the UART data. Valid values
+     range from 0 to 511 (as the data can be up to 9 bits in size).
+   - 2nd item: the list of individual data bits and their ss/es numbers.
  - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
  - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
  - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
@@ -66,8 +68,12 @@ def parity_ok(parity_type, parity_bit, data, num_data_bits):
         return (ones % 2) == 1
     elif parity_type == 'even':
         return (ones % 2) == 0
-    else:
-        raise Exception('Invalid parity type: %d' % parity_type)
+
+class SamplerateError(Exception):
+    pass
+
+class ChannelError(Exception):
+    pass
 
 class Decoder(srd.Decoder):
     api_version = 2
@@ -96,9 +102,12 @@ class Decoder(srd.Decoder):
             'values': (0.0, 0.5, 1.0, 1.5)},
         {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
             'values': ('lsb-first', 'msb-first')},
-        {'id': 'format', 'desc': 'Data format', 'default': 'ascii',
+        {'id': 'format', 'desc': 'Data format', 'default': 'hex',
             'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
-        # TODO: Options to invert the signal(s).
+        {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
+            'values': ('yes', 'no')},
+        {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
+            'values': ('yes', 'no')},
     )
     annotations = (
         ('rx-data', 'RX data'),
@@ -129,50 +138,52 @@ class Decoder(srd.Decoder):
         ('tx', 'TX dump'),
         ('rxtx', 'RX/TX dump'),
     )
+    idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
 
     def putx(self, rxtx, data):
-        s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
-        self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
+        s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
+        self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
 
     def putpx(self, rxtx, data):
-        s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
-        self.put(s - halfbit, self.samplenum + halfbit, self.out_python, data)
+        s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
+        self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
 
     def putg(self, data):
-        s, halfbit = self.samplenum, int(self.bit_width / 2)
-        self.put(s - halfbit, s + halfbit, self.out_ann, data)
+        s, halfbit = self.samplenum, self.bit_width / 2.0
+        self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
 
     def putp(self, data):
-        s, halfbit = self.samplenum, int(self.bit_width / 2)
-        self.put(s - halfbit, s + halfbit, self.out_python, data)
+        s, halfbit = self.samplenum, self.bit_width / 2.0
+        self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
 
     def putbin(self, rxtx, data):
-        s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
-        self.put(s - halfbit, self.samplenum + halfbit, self.out_bin, data)
+        s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
+        self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.samplerate = None
         self.samplenum = 0
         self.frame_start = [-1, -1]
         self.startbit = [-1, -1]
         self.cur_data_bit = [0, 0]
-        self.databyte = [0, 0]
+        self.datavalue = [0, 0]
         self.paritybit = [-1, -1]
         self.stopbit1 = [-1, -1]
         self.startsample = [-1, -1]
         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
         self.oldbit = [1, 1]
-        self.oldpins = [1, 1]
+        self.oldpins = [-1, -1]
         self.databits = [[], []]
 
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
-        self.out_bin = self.register(srd.OUTPUT_BINARY)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
         self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.bw = (self.options['num_data_bits'] + 7) // 8
 
     def metadata(self, key, value):
         if key == srd.SRD_CONF_SAMPLERATE:
-            self.samplerate = value;
+            self.samplerate = value
             # The width of one UART bit in number of samples.
             self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
 
@@ -181,7 +192,9 @@ class Decoder(srd.Decoder):
         # bitpos is the samplenumber which is in the middle of the
         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
         # (if used) or the first stop bit, and so on).
-        bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
+        # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
+        # index of the middle sample within bit window is (bit_width - 1) / 2.
+        bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
         bitpos += bitnum * self.bit_width
         if self.samplenum >= bitpos:
             return True
@@ -211,13 +224,16 @@ class Decoder(srd.Decoder):
 
         self.startbit[rxtx] = signal
 
-        # The startbit must be 0. If not, we report an error.
+        # The startbit must be 0. If not, we report an error and wait
+        # for the next start bit (assuming this one was spurious).
         if self.startbit[rxtx] != 0:
             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
-            # TODO: Abort? Ignore rest of the frame?
+            self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
+            self.state[rxtx] = 'WAIT FOR START BIT'
+            return
 
         self.cur_data_bit[rxtx] = 0
-        self.databyte[rxtx] = 0
+        self.datavalue[rxtx] = 0
         self.startsample[rxtx] = -1
 
         self.state[rxtx] = 'GET DATA BITS'
@@ -236,15 +252,12 @@ class Decoder(srd.Decoder):
 
         # Get the next data bit in LSB-first or MSB-first fashion.
         if self.options['bit_order'] == 'lsb-first':
-            self.databyte[rxtx] >>= 1
-            self.databyte[rxtx] |= \
+            self.datavalue[rxtx] >>= 1
+            self.datavalue[rxtx] |= \
                 (signal << (self.options['num_data_bits'] - 1))
-        elif self.options['bit_order'] == 'msb-first':
-            self.databyte[rxtx] <<= 1
-            self.databyte[rxtx] |= (signal << 0)
         else:
-            raise Exception('Invalid bit order value: %s',
-                            self.options['bit_order'])
+            self.datavalue[rxtx] <<= 1
+            self.datavalue[rxtx] |= (signal << 0)
 
         self.putg([rxtx + 12, ['%d' % signal]])
 
@@ -259,28 +272,61 @@ class Decoder(srd.Decoder):
 
         self.state[rxtx] = 'GET PARITY BIT'
 
-        self.putpx(rxtx, ['DATABITS', rxtx, self.databits[rxtx]])
-        self.putpx(rxtx, ['DATA', rxtx, self.databyte[rxtx]])
-
-        b, f = self.databyte[rxtx], self.options['format']
-        if f == 'ascii':
-            c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
-            self.putx(rxtx, [rxtx, [c]])
-        elif f == 'dec':
-            self.putx(rxtx, [rxtx, [str(b)]])
-        elif f == 'hex':
-            self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
-        elif f == 'oct':
-            self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
-        elif f == 'bin':
-            self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
+        self.putpx(rxtx, ['DATA', rxtx,
+            (self.datavalue[rxtx], self.databits[rxtx])])
+
+        b = self.datavalue[rxtx]
+        formatted = self.format_value(b)
+        if formatted is not None:
+            self.putx(rxtx, [rxtx, [formatted]])
+
+        bdata = b.to_bytes(self.bw, byteorder='big')
+        self.putbin(rxtx, [rxtx, bdata])
+        self.putbin(rxtx, [2, bdata])
+
+        self.databits[rxtx] = []
+
+    def format_value(self, v):
+        # Format value 'v' according to configured options.
+        # Reflects the user selected kind of representation, as well as
+        # the number of data bits in the UART frames.
+
+        fmt, bits = self.options['format'], self.options['num_data_bits']
+
+        # Assume "is printable" for values from 32 to including 126,
+        # below 32 is "control" and thus not printable, above 127 is
+        # "not ASCII" in its strict sense, 127 (DEL) is not printable,
+        # fall back to hex representation for non-printables.
+        if fmt == 'ascii':
+            if v in range(32, 126 + 1):
+                return chr(v)
+            hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
+            return hexfmt.format(v)
+
+        # Mere number to text conversion without prefix and padding
+        # for the "decimal" output format.
+        if fmt == 'dec':
+            return "{:d}".format(v)
+
+        # Padding with leading zeroes for hex/oct/bin formats, but
+        # without a prefix for density -- since the format is user
+        # specified, there is no ambiguity.
+        if fmt == 'hex':
+            digits = (bits + 4 - 1) // 4
+            fmtchar = "X"
+        elif fmt == 'oct':
+            digits = (bits + 3 - 1) // 3
+            fmtchar = "o"
+        elif fmt == 'bin':
+            digits = bits
+            fmtchar = "b"
         else:
-            raise Exception('Invalid data format option: %s' % f)
-
-        self.putbin(rxtx, (rxtx, bytes([b])))
-        self.putbin(rxtx, (2, bytes([b])))
+            fmtchar = None
+        if fmtchar is not None:
+            fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
+            return fmt.format(v)
 
-        self.databits = [[], []]
+        return None
 
     def get_parity_bit(self, rxtx, signal):
         # If no parity is used/configured, skip to the next state immediately.
@@ -297,7 +343,7 @@ class Decoder(srd.Decoder):
         self.state[rxtx] = 'GET STOP BITS'
 
         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
-                     self.databyte[rxtx], self.options['num_data_bits']):
+                     self.datavalue[rxtx], self.options['num_data_bits']):
             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
             self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
         else:
@@ -318,7 +364,7 @@ class Decoder(srd.Decoder):
         # Stop bits must be 1. If not, we report an error.
         if self.stopbit1[rxtx] != 1:
             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
-            self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
+            self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
             # TODO: Abort? Ignore the frame? Other?
 
         self.state[rxtx] = 'WAIT FOR START BIT'
@@ -327,20 +373,27 @@ class Decoder(srd.Decoder):
         self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
 
-            # Note: Ignoring identical samples here for performance reasons
-            # is not possible for this PD, at least not in the current state.
-            # if self.oldpins == pins:
-            #     continue
+            # We want to skip identical samples for performance reasons but,
+            # for now, we can only do that when we are in the idle state
+            # (meaning both channels are waiting for the start bit).
+            if self.state == self.idle_state and self.oldpins == pins:
+                continue
+
             self.oldpins, (rx, tx) = pins, pins
 
+            if self.options['invert_rx'] == 'yes':
+                rx = not rx
+            if self.options['invert_tx'] == 'yes':
+                tx = not tx
+
             # Either RX or TX (but not both) can be omitted.
             has_pin = [rx in (0, 1), tx in (0, 1)]
             if has_pin == [False, False]:
-                raise Exception('Either TX or RX (or both) pins required.')
+                raise ChannelError('Either TX or RX (or both) pins required.')
 
             # State machine.
             for rxtx in (RX, TX):
@@ -360,9 +413,6 @@ class Decoder(srd.Decoder):
                     self.get_parity_bit(rxtx, signal)
                 elif self.state[rxtx] == 'GET STOP BITS':
                     self.get_stop_bits(rxtx, signal)
-                else:
-                    raise Exception('Invalid state: %s' % self.state[rxtx])
 
                 # Save current RX/TX values for the next round.
                 self.oldbit[rxtx] = signal
-
diff --git a/decoders/usb_packet/__init__.py b/decoders/usb_packet/__init__.py
index 06b67b9..f841d20 100644
--- a/decoders/usb_packet/__init__.py
+++ b/decoders/usb_packet/__init__.py
@@ -41,5 +41,4 @@ https://en.wikipedia.org/wiki/USB
 http://www.usb.org/developers/docs/
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/usb_packet/pd.py b/decoders/usb_packet/pd.py
index 8f86cc7..c159202 100644
--- a/decoders/usb_packet/pd.py
+++ b/decoders/usb_packet/pd.py
@@ -33,7 +33,9 @@ Packet:
  - 'ADDR', <addr>
  - 'EP', <ep>
  - 'CRC5', <crc5>
+ - 'CRC5 ERROR', <crc5>
  - 'CRC16', <crc16>
+ - 'CRC16 ERROR', <crc16>
  - 'EOP', <eop>
  - 'FRAMENUM', <framenum>
  - 'DATABYTE', <databyte>
@@ -111,7 +113,7 @@ pids = {
 
     # Special
     '00111100': ['PRE', 'Host-issued preamble; enables downstream bus traffic to low-speed devices'],
-    '00111100': ['ERR', 'Split transaction error handshake'],
+    #'00111100': ['ERR', 'Split transaction error handshake'],
     '00011110': ['SPLIT', 'HS split transaction token'],
     '00101101': ['PING', 'HS flow control probe for a bulk/control EP'],
     '00001111': ['Reserved', 'Reserved PID'],
@@ -142,6 +144,35 @@ def bitstr_to_num(bitstr):
     l.reverse()
     return int(''.join(l), 2)
 
+def reverse_number(num, count):
+    out = list(count * '0')
+    for i in range(0, count):
+        if num >> i & 1:
+            out[i] = '1';
+    return int(''.join(out), 2)
+
+def calc_crc5(bitstr):
+    poly5 = 0x25
+    crc5 = 0x1f
+    for bit in bitstr:
+        crc5 <<= 1
+        if int(bit) != (crc5 >> 5):
+            crc5 ^= poly5
+        crc5 &= 0x1f
+    crc5 ^= 0x1f
+    return reverse_number(crc5, 5)
+
+def calc_crc16(bitstr):
+    poly16 = 0x18005
+    crc16 = 0xffff
+    for bit in bitstr:
+        crc16 <<= 1
+        if int(bit) != (crc16 >> 16):
+            crc16 ^= poly16
+        crc16 &= 0xffff
+    crc16 ^= 0xffff
+    return reverse_number(crc16, 16)
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'usb_packet'
@@ -192,7 +223,6 @@ class Decoder(srd.Decoder):
     )
 
     def __init__(self):
-        self.samplenum = 0
         self.bits = []
         self.packet = []
         self.packet_summary = ''
@@ -221,6 +251,10 @@ class Decoder(srd.Decoder):
         for (bit, ss, es) in self.bits:
             packet += bit
 
+        if len(packet) < 8:
+            self.putp([28, ['Invalid packet (shorter than 8 bits)']])
+            return
+
         # Bits[0:7]: SYNC
         sync = packet[:7 + 1]
         self.ss, self.es = self.bits[0][1], self.bits[7][2]
@@ -234,16 +268,24 @@ class Decoder(srd.Decoder):
             self.putb([0, ['SYNC: %s' % sync, 'SYNC', 'S']])
         self.packet.append(sync)
 
+        if len(packet) < 16:
+            self.putp([28, ['Invalid packet (shorter than 16 bits)']])
+            return
+
         # Bits[8:15]: PID
         pid = packet[8:15 + 1]
-        pidname = pids.get(pid, (pid, ''))[0]
+        pidname = pids.get(pid, ('UNKNOWN', 'Unknown PID'))[0]
         self.ss, self.es = self.bits[8][1], self.bits[15][2]
         self.putpb(['PID', pidname])
         self.putb([2, ['PID: %s' % pidname, pidname, pidname[0]]])
         self.packet.append(pid)
         self.packet_summary += pidname
 
-        if pidname in ('OUT', 'IN', 'SOF', 'SETUP', 'PRE', 'PING'):
+        if pidname in ('OUT', 'IN', 'SOF', 'SETUP', 'PING'):
+            if len(packet) < 32:
+                self.putp([28, ['Invalid packet (shorter than 32 bits)']])
+                return
+
             if pidname == 'SOF':
                 # Bits[16:26]: Framenum
                 framenum = bitstr_to_num(packet[16:26 + 1])
@@ -272,9 +314,14 @@ class Decoder(srd.Decoder):
 
             # Bits[27:31]: CRC5
             crc5 = bitstr_to_num(packet[27:31 + 1])
+            crc5_calc = calc_crc5(packet[16:27])
             self.ss, self.es = self.bits[27][1], self.bits[31][2]
-            self.putpb(['CRC5', crc5])
-            self.putb([6, ['CRC5: 0x%02X' % crc5, 'CRC5', 'C']])
+            if crc5 == crc5_calc:
+                self.putpb(['CRC5', crc5])
+                self.putb([6, ['CRC5: 0x%02X' % crc5, 'CRC5', 'C']])
+            else:
+                self.putpb(['CRC5 ERROR', crc5])
+                self.putb([7, ['CRC5 ERROR: 0x%02X' % crc5, 'CRC5 ERR', 'CE', 'C']])
             self.packet.append(crc5)
         elif pidname in ('DATA0', 'DATA1', 'DATA2', 'MDATA'):
             # Bits[16:packetlen-16]: Data
@@ -290,7 +337,6 @@ class Decoder(srd.Decoder):
                                'DB: %02X' % db, '%02X' % db]])
                 databytes.append(db)
                 self.packet_summary += ' %02X' % db
-                data = data[8:]
             self.packet_summary += ' ]'
 
             # Convenience Python output (no annotation) for all bytes together.
@@ -300,12 +346,19 @@ class Decoder(srd.Decoder):
 
             # Bits[packetlen-16:packetlen]: CRC16
             crc16 = bitstr_to_num(packet[-16:])
+            crc16_calc = calc_crc16(packet[16:-16])
             self.ss, self.es = self.bits[-16][1], self.bits[-1][2]
-            self.putpb(['CRC16', crc16])
-            self.putb([9, ['CRC16: 0x%04X' % crc16, 'CRC16', 'C']])
+            if crc16 == crc16_calc:
+                self.putpb(['CRC16', crc16])
+                self.putb([9, ['CRC16: 0x%04X' % crc16, 'CRC16', 'C']])
+            else:
+                self.putpb(['CRC16 ERROR', crc16])
+                self.putb([10, ['CRC16 ERROR: 0x%04X' % crc16, 'CRC16 ERR', 'CE', 'C']])
             self.packet.append(crc16)
         elif pidname in ('ACK', 'NAK', 'STALL', 'NYET', 'ERR'):
             pass # Nothing to do, these only have SYNC+PID+EOP fields.
+        elif pidname in ('PRE'):
+            pass # Nothing to do, PRE only has SYNC+PID fields.
         else:
             pass # TODO: Handle 'SPLIT' and possibly 'Reserved' packets.
 
@@ -320,7 +373,7 @@ class Decoder(srd.Decoder):
         (ptype, pdata) = data
 
         # We only care about certain packet types for now.
-        if ptype not in ('SOP', 'BIT', 'EOP'):
+        if ptype not in ('SOP', 'BIT', 'EOP', 'ERR'):
             return
 
         # State machine.
@@ -332,12 +385,10 @@ class Decoder(srd.Decoder):
         elif self.state == 'GET BIT':
             if ptype == 'BIT':
                 self.bits.append([pdata, ss, es])
-            elif ptype == 'EOP':
+            elif ptype == 'EOP' or ptype == 'ERR':
                 self.es_packet = es
                 self.handle_packet()
+                self.packet, self.packet_summary = [], ''
                 self.bits, self.state = [], 'WAIT FOR SOP'
             else:
                 pass # TODO: Error
-        else:
-            raise Exception('Invalid state: %s' % self.state)
-
diff --git a/decoders/tlc5620/__init__.py b/decoders/usb_power_delivery/__init__.py
similarity index 88%
copy from decoders/tlc5620/__init__.py
copy to decoders/usb_power_delivery/__init__.py
index c615760..4ba626a 100644
--- a/decoders/tlc5620/__init__.py
+++ b/decoders/usb_power_delivery/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2015 Google, Inc
 ##
 ## 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
@@ -19,8 +19,7 @@
 ##
 
 '''
-The Texas Instruments TLC5620 is an 8-bit quad DAC.
+USB Power Delivery - baseband protocol decoder / checker.
 '''
 
 from .pd import *
-
diff --git a/decoders/usb_power_delivery/pd.py b/decoders/usb_power_delivery/pd.py
new file mode 100644
index 0000000..48db41b
--- /dev/null
+++ b/decoders/usb_power_delivery/pd.py
@@ -0,0 +1,579 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Google, Inc
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import struct
+import zlib   # for crc32
+
+# BMC encoding with a 600kHz datarate
+UI_US = 1000000/600000.0
+
+# Threshold to discriminate half-1 from 0 in Binary Mark Conding
+THRESHOLD_US = (UI_US + 2 * UI_US) / 2
+
+# Control Message type
+CTRL_TYPES = {
+    0: 'reserved',
+    1: 'GOOD CRC',
+    2: 'GOTO MIN',
+    3: 'ACCEPT',
+    4: 'REJECT',
+    5: 'PING',
+    6: 'PS RDY',
+    7: 'GET SOURCE CAP',
+    8: 'GET SINK CAP',
+    9: 'DR SWAP',
+    10: 'PR SWAP',
+    11: 'VCONN SWAP',
+    12: 'WAIT',
+    13: 'SOFT RESET',
+    14: 'reserved',
+    15: 'reserved'
+}
+
+# Data message type
+DATA_TYPES = {
+    1: 'SOURCE CAP',
+    2: 'REQUEST',
+    3: 'BIST',
+    4: 'SINK CAP',
+    15: 'VDM'
+}
+
+# 4b5b encoding of the symbols
+DEC4B5B = [
+    0x10,   # Error      00000
+    0x10,   # Error      00001
+    0x10,   # Error      00010
+    0x10,   # Error      00011
+    0x10,   # Error      00100
+    0x10,   # Error      00101
+    0x13,   # Sync-3     00110
+    0x14,   # RST-1      00111
+    0x10,   # Error      01000
+    0x01,   # 1 = 0001   01001
+    0x04,   # 4 = 0100   01010
+    0x05,   # 5 = 0101   01011
+    0x10,   # Error      01100
+    0x16,   # EOP        01101
+    0x06,   # 6 = 0110   01110
+    0x07,   # 7 = 0111   01111
+    0x10,   # Error      10000
+    0x12,   # Sync-2     10001
+    0x08,   # 8 = 1000   10010
+    0x09,   # 9 = 1001   10011
+    0x02,   # 2 = 0010   10100
+    0x03,   # 3 = 0011   10101
+    0x0A,   # A = 1010   10110
+    0x0B,   # B = 1011   10111
+    0x11,   # Sync-1     11000
+    0x15,   # RST-2      11001
+    0x0C,   # C = 1100   11010
+    0x0D,   # D = 1101   11011
+    0x0E,   # E = 1110   11100
+    0x0F,   # F = 1111   11101
+    0x00,   # 0 = 0000   11110
+    0x10,   # Error      11111
+]
+SYM_ERR = 0x10
+SYNC1 = 0x11
+SYNC2 = 0x12
+SYNC3 = 0x13
+RST1 = 0x14
+RST2 = 0x15
+EOP = 0x16
+SYNC_CODES = [SYNC1, SYNC2, SYNC3]
+HRST_CODES = [RST1, RST1, RST1, RST2]
+
+START_OF_PACKETS = {
+    (SYNC1, SYNC1, SYNC1, SYNC2): 'SOP',
+    (SYNC1, SYNC1, SYNC3, SYNC3): "SOP'",
+    (SYNC1, SYNC3, SYNC1, SYNC3): 'SOP"',
+    (SYNC1, RST2,  RST2,  SYNC3): "SOP' Debug",
+    (SYNC1, RST2,  SYNC3, SYNC2): 'SOP" Debug',
+    (RST1,  SYNC1, RST1,  SYNC3): 'Cable Reset',
+    (RST1,  RST1,  RST1,   RST2): 'Hard Reset',
+}
+
+SYM_NAME = [
+    ['0x0', '0'],
+    ['0x1', '1'],
+    ['0x2', '2'],
+    ['0x3', '3'],
+    ['0x4', '4'],
+    ['0x5', '5'],
+    ['0x6', '6'],
+    ['0x7', '7'],
+    ['0x8', '8'],
+    ['0x9', '9'],
+    ['0xA', 'A'],
+    ['0xB', 'B'],
+    ['0xC', 'C'],
+    ['0xD', 'D'],
+    ['0xE', 'E'],
+    ['0xF', 'F'],
+    ['ERROR', 'X'],
+    ['SYNC-1', 'S1'],
+    ['SYNC-2', 'S2'],
+    ['SYNC-3', 'S3'],
+    ['RST-1', 'R1'],
+    ['RST-2', 'R2'],
+    ['EOP', '#'],
+]
+
+RDO_FLAGS = {
+    (1 << 24): 'no_suspend',
+    (1 << 25): 'comm_cap',
+    (1 << 26): 'cap_mismatch',
+    (1 << 27): 'give_back'
+}
+PDO_TYPE = ['', 'BATT:', 'VAR:', '<bad>']
+PDO_FLAGS = {
+    (1 << 29): 'dual_role_power',
+    (1 << 28): 'suspend',
+    (1 << 27): 'ext',
+    (1 << 26): 'comm_cap',
+    (1 << 25): 'dual_role_data'
+}
+
+BIST_MODES = {
+        0: 'Receiver',
+        1: 'Transmit',
+        2: 'Counters',
+        3: 'Carrier 0',
+        4: 'Carrier 1',
+        5: 'Carrier 2',
+        6: 'Carrier 3',
+        7: 'Eye',
+}
+
+VDM_CMDS = {
+        1: 'Disc Ident',
+        2: 'Disc SVID',
+        3: 'Disc Mode',
+        4: 'Enter Mode',
+        5: 'Exit Mode',
+        6: 'Attention',
+        # 16..31: SVID Specific Commands
+        # DisplayPort Commands
+        16: 'DP Status',
+        17: 'DP Configure',
+}
+VDM_ACK = ['REQ', 'ACK', 'NAK', 'BSY']
+
+class SamplerateError(Exception):
+    pass
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'usb_power_delivery'
+    name = 'USB PD'
+    longname = 'USB Power Delivery'
+    desc = 'USB Power Delivery protocol.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['usb_pd']
+    channels = (
+        {'id': 'cc', 'name': 'CC', 'desc': 'Control channel'},
+    )
+    options = (
+        {'id': 'fulltext', 'desc': 'full text decoding of the packet',
+         'default': 'no', 'values': ('yes', 'no')},
+    )
+    annotations = (
+        ('type', 'Packet Type'),
+        ('Preamble', 'Preamble'),
+        ('SOP', 'Start of Packet'),
+        ('Head', 'Header'),
+        ('Data', 'Data'),
+        ('CRC', 'Checksum'),
+        ('EOP', 'End Of Packet'),
+        ('Sym', '4b5b symbols'),
+        ('warnings', 'Warnings'),
+        ('src', 'Source Message'),
+        ('snk', 'Sink Message'),
+        ('payload', 'Payload'),
+        ('text', 'Plain text'),
+    )
+    annotation_rows = (
+       ('4B5B', 'symbols', (7, )),
+       ('Phase', 'parts', (1, 2, 3, 4, 5, 6, )),
+       ('payload', 'Payload', (11, )),
+       ('type', 'Type', (0, 9, 10, )),
+       ('warnings', 'Warnings', (8, )),
+       ('text', 'Full text', (12, )),
+    )
+    binary = (
+        ('raw-data', 'RAW binary data'),
+    )
+
+    def get_request(self, rdo):
+        pos = (rdo >> 28) & 7
+        op_ma = ((rdo >> 10) & 0x3ff) * 10
+        max_ma = (rdo & 0x3ff) * 10
+        flags = ''
+        for f in RDO_FLAGS.keys():
+            if rdo & f:
+                flags += ' ' + RDO_FLAGS[f]
+        return '[%d]%d/%d mA%s' % (pos, op_ma, max_ma, flags)
+
+    def get_source_cap(self, pdo):
+        t = (pdo >> 30) & 3
+        if t == 0:
+            mv = ((pdo >> 10) & 0x3ff) * 50
+            ma = ((pdo >> 0) & 0x3ff) * 10
+            p = '%.1fV %.1fA' % (mv/1000.0, ma/1000.0)
+        elif t == 1:
+            minv = ((pdo >> 10) & 0x3ff) * 50
+            maxv = ((pdo >> 20) & 0x3ff) * 50
+            mw = ((pdo >> 0) & 0x3ff) * 250
+            p = '%.1f/%.1fV %.1fW' % (minv/1000.0, maxv/1000.0, mw/1000.0)
+        elif t == 2:
+            minv = ((pdo >> 10) & 0x3ff) * 50
+            maxv = ((pdo >> 20) & 0x3ff) * 50
+            ma = ((pdo >> 0) & 0x3ff) * 10
+            p = '%.1f/%.1fV %.1fA' % (minv/1000.0, maxv/1000.0, ma/1000.0)
+        else:
+            p = ''
+        flags = ''
+        for f in PDO_FLAGS.keys():
+            if pdo & f:
+                flags += ' ' + PDO_FLAGS[f]
+        return '%s%s%s' % (PDO_TYPE[t], p, flags)
+
+    def get_sink_cap(self, pdo):
+        t = (pdo >> 30) & 3
+        if t == 0:
+            mv = ((pdo >> 10) & 0x3ff) * 50
+            ma = ((pdo >> 0) & 0x3ff) * 10
+            p = '%.1fV %.1fA' % (mv/1000.0, ma/1000.0)
+        elif t == 1:
+            minv = ((pdo >> 10) & 0x3ff) * 50
+            maxv = ((pdo >> 20) & 0x3ff) * 50
+            mw = ((pdo >> 0) & 0x3ff) * 250
+            p = '%.1f/%.1fV %.1fW' % (minv/1000.0, maxv/1000.0, mw/1000.0)
+        elif t == 2:
+            minv = ((pdo >> 10) & 0x3ff) * 50
+            maxv = ((pdo >> 20) & 0x3ff) * 50
+            ma = ((pdo >> 0) & 0x3ff) * 10
+            p = '%.1f/%.1fV %.1fA' % (minv/1000.0, maxv/1000.0, ma/1000.0)
+        else:
+            p = ''
+        flags = ''
+        for f in PDO_FLAGS.keys():
+            if pdo & f:
+                flags += ' ' + PDO_FLAGS[f]
+        return '%s%s%s' % (PDO_TYPE[t], p, flags)
+
+    def get_vdm(self, idx, data):
+        if idx == 0:    # VDM header
+            vid = data >> 16
+            struct = data & (1 << 15)
+            txt = 'VDM'
+            if struct:  # Structured VDM
+                cmd = data & 0x1f
+                src = data & (1 << 5)
+                ack = (data >> 6) & 3
+                pos = (data >> 8) & 7
+                ver = (data >> 13) & 3
+                txt = VDM_ACK[ack] + ' '
+                txt += VDM_CMDS[cmd] if cmd in VDM_CMDS else 'cmd?'
+                txt += ' pos %d' % (pos) if pos else ' '
+            else:   # Unstructured VDM
+                txt = 'unstruct [%04x]' % (data & 0x7fff)
+            txt += ' SVID:%04x' % (vid)
+        else:   # VDM payload
+            txt = 'VDO:%08x' % (data)
+        return txt
+
+    def get_bist(self, idx, data):
+        mode = data >> 28
+        counter = data & 0xffff
+        mode_name = BIST_MODES[mode] if mode in BIST_MODES else 'INVALID'
+        if mode == 2:
+            mode_name = 'Counter[= %d]' % (counter)
+        # TODO check all 0 bits are 0 / emit warnings
+        return 'mode %s' % (mode_name) if idx == 0 else 'invalid BRO'
+
+    def putpayload(self, s0, s1, idx):
+        t = self.head_type()
+        txt = '???'
+        if t == 2:
+            txt = self.get_request(self.data[idx])
+        elif t == 1:
+            txt = self.get_source_cap(self.data[idx])
+        elif t == 4:
+            txt = self.get_sink_cap(self.data[idx])
+        elif t == 15:
+            txt = self.get_vdm(idx, self.data[idx])
+        elif t == 3:
+            txt = self.get_bist(idx, self.data[idx])
+        self.putx(s0, s1, [11, [txt, txt]])
+        self.text += ' - ' + txt
+
+    def puthead(self):
+        ann_type = 9 if self.head_power_role() else 10
+        role = 'SRC' if self.head_power_role() else 'SNK'
+        if self.head_data_role() != self.head_power_role():
+            role += '/DFP' if self.head_data_role() else '/UFP'
+        t = self.head_type()
+        if self.head_count() == 0:
+            shortm = CTRL_TYPES[t]
+        else:
+            shortm = DATA_TYPES[t] if t in DATA_TYPES else 'DAT???'
+
+        longm = '{:s}[{:d}]:{:s}'.format(role, self.head_id(), shortm)
+        self.putx(0, -1, [ann_type, [longm, shortm]])
+        self.text += longm
+
+    def head_id(self):
+        return (self.head >> 9) & 7
+
+    def head_power_role(self):
+        return (self.head >> 8) & 1
+
+    def head_data_role(self):
+        return (self.head >> 5) & 1
+
+    def head_rev(self):
+        return ((self.head >> 6) & 3) + 1
+
+    def head_type(self):
+        return self.head & 0xF
+
+    def head_count(self):
+        return (self.head >> 12) & 7
+
+    def putx(self, s0, s1, data):
+        self.put(self.edges[s0], self.edges[s1], self.out_ann, data)
+
+    def putwarn(self, longm, shortm):
+        self.putx(0, -1, [8, [longm, shortm]])
+
+    def compute_crc32(self):
+        bdata = struct.pack('<H'+'I'*len(self.data), self.head & 0xffff,
+                            *tuple([d & 0xffffffff for d in self.data]))
+        return zlib.crc32(bdata)
+
+    def rec_sym(self, i, sym):
+        self.putx(i, i+5, [7, SYM_NAME[sym]])
+
+    def get_sym(self, i, rec=True):
+        v = (self.bits[i] | (self.bits[i+1] << 1) | (self.bits[i+2] << 2) |
+             (self.bits[i+3] << 3) | (self.bits[i+4] << 4))
+        sym = DEC4B5B[v]
+        if rec:
+            self.rec_sym(i, sym)
+        return sym
+
+    def get_short(self):
+        i = self.idx
+        # Check it's not a truncated packet
+        if len(self.bits) - i <= 20:
+            self.putwarn('Truncated', '!')
+            return 0x0BAD
+        k = [self.get_sym(i), self.get_sym(i+5),
+             self.get_sym(i+10), self.get_sym(i+15)]
+        # TODO check bad symbols
+        val = k[0] | (k[1] << 4) | (k[2] << 8) | (k[3] << 12)
+        self.idx += 20
+        return val
+
+    def get_word(self):
+        lo = self.get_short()
+        hi = self.get_short()
+        return lo | (hi << 16)
+
+    def find_corrupted_sop(self, k):
+        # Start of packet are valid even if they have only 3 correct symbols
+        # out of 4.
+        for seq in START_OF_PACKETS.keys():
+            if [k[i] == seq[i] for i in range(len(k))].count(True) >= 3:
+                return START_OF_PACKETS[seq]
+        return None
+
+    def scan_eop(self):
+        for i in range(len(self.bits) - 19):
+            k = (self.get_sym(i, rec=False), self.get_sym(i+5, rec=False),
+                 self.get_sym(i+10, rec=False), self.get_sym(i+15, rec=False))
+            sym = START_OF_PACKETS[k] if k in START_OF_PACKETS else None
+            if not sym:
+                sym = self.find_corrupted_sop(k)
+            # We have an interesting symbol sequence
+            if sym:
+                # annotate the preamble
+                self.putx(0, i, [1, ['Preamble', '...']])
+                # annotate each symbol
+                self.rec_sym(i, k[0])
+                self.rec_sym(i+5, k[1])
+                self.rec_sym(i+10, k[2])
+                self.rec_sym(i+15, k[3])
+                if sym == 'Hard Reset':
+                    self.text += 'HRST'
+                    return -1   # Hard reset
+                elif sym == 'Cable Reset':
+                    self.text += 'CRST'
+                    return -1   # Cable reset
+                else:
+                    self.putx(i, i+20, [2, [sym, 'S']])
+                return i+20
+        self.putx(0, len(self.bits), [1, ['Junk???', 'XXX']])
+        self.text += 'Junk???'
+        self.putwarn('No start of packet found', 'XXX')
+        return -1   # No Start Of Packet
+
+    def __init__(self):
+        self.samplerate = None
+        self.idx = 0
+        self.packet_seq = 0
+        self.samplenum = 0
+        self.previous = 0
+        self.oldpins = [0]
+        self.startsample = None
+        self.bits = []
+        self.edges = []
+        self.bad = []
+        self.half_one = False
+        self.start_one = 0
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+            # 0 is 2 UI, space larger than 1.5x 0 is definitely wrong
+            self.maxbit = self.us2samples(3 * UI_US)
+            # duration threshold between half 1 and 0
+            self.threshold = self.us2samples(THRESHOLD_US)
+
+    def start(self):
+        self.out_python = self.register(srd.OUTPUT_PYTHON)
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+        self.out_bitrate = self.register(
+            srd.OUTPUT_META,
+            meta=(int, 'Bitrate', 'Bitrate during the packet')
+        )
+
+    def us2samples(self, us):
+        return int(us * self.samplerate / 1000000)
+
+    def decode_packet(self):
+        self.data = []
+        self.idx = 0
+        self.text = ''
+
+        if len(self.edges) < 50:
+            return  # Not a real PD packet
+
+        self.packet_seq += 1
+        tstamp = float(self.startsample) / self.samplerate
+        self.text += '#%-4d (%8.6fms): ' % (self.packet_seq, tstamp*1000)
+
+        self.idx = self.scan_eop()
+        if self.idx < 0:
+            # Full text trace of the issue
+            self.putx(0, self.idx, [12, [self.text, '...']])
+            return  # No real packet: ABORT
+
+        # Packet header
+        self.head = self.get_short()
+        self.putx(self.idx-20, self.idx, [3, ['H:%04x' % (self.head), 'HD']])
+        self.puthead()
+
+        # Decode data payload
+        for i in range(self.head_count()):
+            self.data.append(self.get_word())
+            self.putx(self.idx-40, self.idx,
+                      [4, ['[%d]%08x' % (i, self.data[i]), 'D%d' % (i)]])
+            self.putpayload(self.idx-40, self.idx, i)
+
+        # CRC check
+        self.crc = self.get_word()
+        ccrc = self.compute_crc32()
+        if self.crc != ccrc:
+            self.putwarn('Bad CRC %08x != %08x' % (self.crc, ccrc), 'CRC!')
+        self.putx(self.idx-40, self.idx, [5, ['CRC:%08x' % (self.crc), 'CRC']])
+
+        # End of Packet
+        if len(self.bits) >= self.idx + 5 and self.get_sym(self.idx) == EOP:
+            self.putx(self.idx, self.idx + 5, [6, ['EOP', 'E']])
+            self.idx += 5
+        else:
+            self.putwarn('No EOP', 'EOP!')
+        # Full text trace
+        if self.options['fulltext'] == 'yes':
+            self.putx(0, self.idx, [12, [self.text, '...']])
+
+        # Meta data for bitrate
+        ss, es = self.edges[0], self.edges[-1]
+        bitrate = self.samplerate*len(self.bits) / float(es - ss)
+        self.put(es, ss, self.out_bitrate, int(bitrate))
+        # Raw binary data (BMC decoded)
+        self.put(es, ss, self.out_binary, [0, bytes(self.bits)])
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        for (self.samplenum, pins) in data:
+            # find edges ...
+            if self.oldpins == pins:
+                continue
+
+            self.oldpins, (cc, ) = pins, pins
+
+            # First sample of the packet, just record the start date
+            if not self.startsample:
+                self.startsample = self.samplenum
+                self.previous = self.samplenum
+                continue
+
+            diff = self.samplenum - self.previous
+
+            # Large idle: use it as the end of packet
+            if diff > self.maxbit:
+                # the last edge of the packet
+                self.edges.append(self.previous)
+                # Export the packet
+                self.decode_packet()
+                # Reset for next packet
+                self.startsample = self.samplenum
+                self.bits = []
+                self.edges = []
+                self.bad = []
+                self.half_one = False
+                self.start_one = 0
+            else:   # add the bit to the packet
+                is_zero = diff > self.threshold
+                if is_zero and not self.half_one:
+                    self.bits.append(0)
+                    self.edges.append(self.previous)
+                elif not is_zero and self.half_one:
+                    self.bits.append(1)
+                    self.edges.append(self.start_one)
+                    self.half_one = False
+                elif not is_zero and not self.half_one:
+                    self.half_one = True
+                    self.start_one = self.previous
+                else:   # Invalid BMC sequence
+                    self.bad.append((self.start_one, self.previous))
+                    # TODO try to recover
+                    self.bits.append(0)
+                    self.edges.append(self.previous)
+                    self.half_one = False
+            self.previous = self.samplenum
diff --git a/decoders/usb_request/__init__.py b/decoders/usb_request/__init__.py
new file mode 100644
index 0000000..7a156ff
--- /dev/null
+++ b/decoders/usb_request/__init__.py
@@ -0,0 +1,50 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Stefan Brüns <stefan.bruens at rwth-aachen.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+'''
+This decoder stacks on top of the 'usb_packet' PD and decodes the USB
+(low-speed and full-speed) transactions.
+
+Transactions and requests are tracked per device address and endpoint.
+
+Tracking of CONTROL requests is quite accurate, as these always start with
+a SETUP token and are completed by an IN or OUT transaction, the status
+packet. All transactions during the DATA stage are combined.
+
+For BULK and INTERRUPT requests, each transaction starts with an IN or OUT
+request, and is considered completed after the first transaction containing
+data has been ACKed. Normally a request is only completed after a short or
+zero length packet, but this would require knowledge about the max packet
+size of an endpoint.
+
+All INTERRUPT requests are treated as BULK requests, as on the link layer
+both are identical.
+
+The PCAP binary output contains 'SUBMIT' and 'COMPLETE' records. For
+CONTROL request, the SUBMIT contains the SETUP request, the data is
+either contained in the SUBMIT (Host-to-Device) or the COMPLETE
+(Device-to-Host) record.
+
+Details:
+https://en.wikipedia.org/wiki/USB
+http://www.usb.org/developers/docs/
+'''
+
+from .pd import Decoder
diff --git a/decoders/usb_request/pd.py b/decoders/usb_request/pd.py
new file mode 100644
index 0000000..bb7aedc
--- /dev/null
+++ b/decoders/usb_request/pd.py
@@ -0,0 +1,359 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2015 Stefan Brüns <stefan.bruens at rwth-aachen.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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+import struct
+
+class SamplerateError(Exception):
+    pass
+
+class pcap_usb_pkt():
+    # Linux usbmon format, see Documentation/usb/usbmon.txt
+    h  = b'\x00\x00\x00\x00' # ID part 1
+    h += b'\x00\x00\x00\x00' # ID part 2
+    h += b'C'                # 'S'ubmit / 'C'omplete / 'E'rror
+    h += b'\x03'             # ISO (0), Intr, Control, Bulk (3)
+    h += b'\x00'             # Endpoint
+    h += b'\x00'             # Device address
+    h += b'\x00\x00'         # Bus number
+    h += b'-'                # Setup tag - 0: Setup present, '-' otherwise
+    h += b'<'                # Data tag - '<' no data, 0 otherwise
+    # Timestamp
+    h += b'\x00\x00\x00\x00' # TS seconds part 1
+    h += b'\x00\x00\x00\x00' # TS seconds part 2
+    h += b'\x00\x00\x00\x00' # TS useconds
+    #
+    h += b'\x00\x00\x00\x00' # Status 0: OK
+    h += b'\x00\x00\x00\x00' # URB length
+    h += b'\x00\x00\x00\x00' # Data length
+    # Setup packet data, valid if setup tag == 0
+    h += b'\x00'             # bmRequestType
+    h += b'\x00'             # bRequest
+    h += b'\x00\x00'         # wValue
+    h += b'\x00\x00'         # wIndex
+    h += b'\x00\x00'         # wLength
+    #
+    h += b'\x00\x00\x00\x00' # ISO/interrupt interval
+    h += b'\x00\x00\x00\x00' # ISO start frame
+    h += b'\x00\x00\x00\x00' # URB flags
+    h += b'\x00\x00\x00\x00' # Number of ISO descriptors
+
+    def __init__(self, req, ts, is_submit):
+        self.header = bytearray(pcap_usb_pkt.h)
+        self.data = b''
+        self.set_urbid(req['id'])
+        self.set_urbtype('S' if is_submit else 'C')
+        self.set_timestamp(ts)
+        self.set_addr_ep(req['addr'], req['ep'])
+        if req['type'] in ('SETUP IN', 'SETUP OUT'):
+            self.set_transfertype(2) # Control
+            self.set_setup(req['setup_data'])
+        if req['type'] in ('BULK IN'):
+            self.set_addr_ep(req['addr'], 0x80 | req['ep'])
+        self.set_data(req['data'])
+
+    def set_urbid(self, urbid):
+        self.header[4:8] = struct.pack('>I', urbid)
+
+    def set_urbtype(self, urbtype):
+        self.header[8] = ord(urbtype)
+
+    def set_transfertype(self, transfertype):
+        self.header[9] = transfertype
+
+    def set_addr_ep(self, addr, ep):
+        self.header[11] = addr
+        self.header[10] = ep
+
+    def set_timestamp(self, ts):
+        self.timestamp = ts
+        self.header[20:24] = struct.pack('>I', ts[0]) # seconds
+        self.header[24:28] = struct.pack('>I', ts[1]) # microseconds
+
+    def set_data(self, data):
+        self.data = data
+        self.header[15] = 0
+        self.header[36:40] = struct.pack('>I', len(data))
+
+    def set_setup(self, data):
+        self.header[14] = 0
+        self.header[40:48] = data
+
+    def packet(self):
+        return bytes(self.header) + bytes(self.data)
+
+    def record_header(self):
+        # See https://wiki.wireshark.org/Development/LibpcapFileFormat.
+        (secs, usecs) = self.timestamp
+        h  = struct.pack('>I', secs) # TS seconds
+        h += struct.pack('>I', usecs) # TS microseconds
+        # No truncation, so both lengths are the same.
+        h += struct.pack('>I', len(self)) # Captured len (usb hdr + data)
+        h += struct.pack('>I', len(self)) # Original len
+        return h
+
+    def __len__(self):
+        return 64 + len(self.data)
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'usb_request'
+    name = 'USB request'
+    longname = 'Universal Serial Bus (LS/FS) transaction/request'
+    desc = 'USB (low-speed and full-speed) transaction/request protocol.'
+    license = 'gplv2+'
+    inputs = ['usb_packet']
+    outputs = ['usb_request']
+    annotations = (
+        ('request-setup-read', 'Setup: Device-to-host'),
+        ('request-setup-write', 'Setup: Host-to-device'),
+        ('request-bulk-read', 'Bulk: Device-to-host'),
+        ('request-bulk-write', 'Bulk: Host-to-device'),
+        ('errors', 'Unexpected packets'),
+    )
+    annotation_rows = (
+        ('request', 'USB requests', tuple(range(4))),
+        ('errors', 'Errors', (4,)),
+    )
+    binary = (
+        ('pcap', 'PCAP format'),
+    )
+
+    def __init__(self):
+        self.samplerate = None
+        self.request = {}
+        self.request_id = 0
+        self.transaction_state = 'IDLE'
+        self.ss_transaction = None
+        self.es_transaction = None
+        self.transaction_ep = None
+        self.transaction_addr = None
+        self.wrote_pcap_header = False
+
+    def putr(self, ss, es, data):
+        self.put(ss, es, self.out_ann, data)
+
+    def putb(self, ts, data):
+        self.put(ts, ts, self.out_binary, data)
+
+    def pcap_global_header(self):
+        # See https://wiki.wireshark.org/Development/LibpcapFileFormat.
+        h  = b'\xa1\xb2\xc3\xd4' # Magic, indicate microsecond ts resolution
+        h += b'\x00\x02'         # Major version 2
+        h += b'\x00\x04'         # Minor version 4
+        h += b'\x00\x00\x00\x00' # Correction vs. UTC, seconds
+        h += b'\x00\x00\x00\x00' # Timestamp accuracy
+        h += b'\xff\xff\xff\xff' # Max packet len
+        # LINKTYPE_USB_LINUX_MMAPPED 220
+        # Linux usbmon format, see Documentation/usb/usbmon.txt.
+        h += b'\x00\x00\x00\xdc' # Link layer
+        return h
+
+    def metadata(self, key, value):
+        if key == srd.SRD_CONF_SAMPLERATE:
+            self.samplerate = value
+            self.secs_per_sample = float(1) / float(self.samplerate)
+
+    def start(self):
+        self.out_binary = self.register(srd.OUTPUT_BINARY)
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+
+    def handle_transfer(self):
+        request_started = 0
+        request_end = self.handshake in ('ACK', 'STALL', 'timeout')
+        ep = self.transaction_ep
+        addr = self.transaction_addr
+        if not (addr, ep) in self.request:
+            self.request[(addr, ep)] = {'setup_data': [], 'data': [],
+                'type': None, 'ss': self.ss_transaction, 'es': None,
+                'id': self.request_id, 'addr': addr, 'ep': ep}
+            self.request_id += 1
+            request_started = 1
+        request = self.request[(addr,ep)]
+
+        # BULK or INTERRUPT transfer
+        if request['type'] in (None, 'BULK IN') and self.transaction_type == 'IN':
+            request['type'] = 'BULK IN'
+            request['data'] += self.transaction_data
+            request['es'] = self.es_transaction
+            self.handle_request(request_started, request_end)
+        elif request['type'] in (None, 'BULK OUT') and self.transaction_type == 'OUT':
+            request['type'] = 'BULK OUT'
+            request['data'] += self.transaction_data
+            request['es'] = self.es_transaction
+            self.handle_request(request_started, request_end)
+
+        # CONTROL, SETUP stage
+        elif request['type'] is None and self.transaction_type == 'SETUP':
+            request['setup_data'] = self.transaction_data
+            request['wLength'] = struct.unpack('<H',
+                bytes(self.transaction_data[6:8]))[0]
+            if self.transaction_data[0] & 0x80:
+                request['type'] = 'SETUP IN'
+                self.handle_request(1, 0)
+            else:
+                request['type'] = 'SETUP OUT'
+                self.handle_request(request['wLength'] == 0, 0)
+
+        # CONTROL, DATA stage
+        elif request['type'] == 'SETUP IN' and self.transaction_type == 'IN':
+            request['data'] += self.transaction_data
+
+        elif request['type'] == 'SETUP OUT' and self.transaction_type == 'OUT':
+            request['data'] += self.transaction_data
+            if request['wLength'] == len(request['data']):
+                self.handle_request(1, 0)
+
+        # CONTROL, STATUS stage
+        elif request['type'] == 'SETUP IN' and self.transaction_type == 'OUT':
+            request['es'] = self.es_transaction
+            self.handle_request(0, request_end)
+
+        elif request['type'] == 'SETUP OUT' and self.transaction_type == 'IN':
+            request['es'] = self.es_transaction
+            self.handle_request(0, request_end)
+
+        else:
+            return
+
+        return
+
+    def ts_from_samplenum(self, sample):
+        ts = float(sample) * self.secs_per_sample
+        return (int(ts), int((ts % 1.0) * 1e6))
+
+    def write_pcap_header(self):
+        if not self.wrote_pcap_header:
+            self.put(0, 0, self.out_binary, [0, self.pcap_global_header()])
+            self.wrote_pcap_header = True
+
+    def request_summary(self, request):
+        s = '['
+        if request['type'] in ('SETUP IN', 'SETUP OUT'):
+            for b in request['setup_data']:
+                s += ' %02X' % b
+            s += ' ]['
+        for b in request['data']:
+            s += ' %02X' % b
+        s += ' ] : %s' % self.handshake
+        return s
+
+    def handle_request(self, request_start, request_end):
+        if request_start != 1 and request_end != 1:
+            return
+        self.write_pcap_header()
+        ep = self.transaction_ep
+        addr = self.transaction_addr
+        request = self.request[(addr, ep)]
+
+        ss, es = request['ss'], request['es']
+
+        if request_start == 1:
+            # Issue PCAP 'SUBMIT' packet.
+            ts = self.ts_from_samplenum(ss)
+            pkt = pcap_usb_pkt(request, ts, True)
+            self.putb(ss, [0, pkt.record_header()])
+            self.putb(ss, [0, pkt.packet()])
+
+        if request_end == 1:
+            # Write annotation.
+            summary = self.request_summary(request)
+            if request['type'] == 'SETUP IN':
+                self.putr(ss, es, [0, ['SETUP in: %s' % summary]])
+            elif request['type'] == 'SETUP OUT':
+                self.putr(ss, es, [1, ['SETUP out: %s' % summary]])
+            elif request['type'] == 'BULK IN':
+                self.putr(ss, es, [2, ['BULK in: %s' % summary]])
+            elif request['type'] == 'BULK OUT':
+                self.putr(ss, es, [3, ['BULK out: %s' % summary]])
+
+            # Issue PCAP 'COMPLETE' packet.
+            ts = self.ts_from_samplenum(es)
+            pkt = pcap_usb_pkt(request, ts, False)
+            self.putb(ss, [0, pkt.record_header()])
+            self.putb(ss, [0, pkt.packet()])
+            del self.request[(addr, ep)]
+
+    def decode(self, ss, es, data):
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
+        ptype, pdata = data
+
+        # We only care about certain packet types for now.
+        if ptype not in ('PACKET'):
+            return
+
+        pcategory, pname, pinfo = pdata
+
+        if pcategory == 'TOKEN':
+            if pname == 'SOF':
+                return
+            if self.transaction_state == 'TOKEN RECEIVED':
+                transaction_timeout = self.es_transaction
+                # Token length is 35 bits, timeout is 16..18 bit times
+                # (USB 2.0 7.1.19.1).
+                transaction_timeout += int((self.es_transaction - self.ss_transaction) / 2)
+                if ss > transaction_timeout:
+                    self.es_transaction = transaction_timeout
+                    self.handshake = 'timeout'
+                    self.handle_transfer()
+                    self.transaction_state = 'IDLE'
+
+            if self.transaction_state != 'IDLE':
+                self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
+                    (pname, self.transaction_state)]])
+                return
+
+            sync, pid, addr, ep, crc5 = pinfo
+            self.transaction_data = []
+            self.ss_transaction = ss
+            self.es_transaction = es
+            self.transaction_state = 'TOKEN RECEIVED'
+            self.transaction_ep = ep
+            self.transaction_addr = addr
+            self.transaction_type = pname # IN OUT SETUP
+
+        elif pcategory == 'DATA':
+            if self.transaction_state != 'TOKEN RECEIVED':
+                self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
+                    (pname, self.transaction_state)]])
+                return
+
+            self.transaction_data = pinfo[2]
+            self.transaction_state = 'DATA RECEIVED'
+
+        elif pcategory == 'HANDSHAKE':
+            if self.transaction_state not in ('TOKEN RECEIVED', 'DATA RECEIVED'):
+                self.putr(ss, es, [4, ['ERR: received %s token in state %s' %
+                    (pname, self.transaction_state)]])
+                return
+
+            self.handshake = pname
+            self.transaction_state = 'IDLE'
+            self.es_transaction = es
+            self.handle_transfer()
+
+        elif pname == 'PRE':
+            return
+
+        else:
+            self.putr(ss, es, [4, ['ERR: received unhandled %s token in state %s' %
+                (pname, self.transaction_state)]])
+            return
diff --git a/decoders/usb_signalling/__init__.py b/decoders/usb_signalling/__init__.py
index 2311b1f..b2ceb4d 100644
--- a/decoders/usb_signalling/__init__.py
+++ b/decoders/usb_signalling/__init__.py
@@ -48,5 +48,4 @@ https://en.wikipedia.org/wiki/USB
 http://www.usb.org/developers/docs/
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/usb_signalling/pd.py b/decoders/usb_signalling/pd.py
index 8c6a9c3..c60075c 100644
--- a/decoders/usb_signalling/pd.py
+++ b/decoders/usb_signalling/pd.py
@@ -33,12 +33,15 @@ Packet:
  - 'BIT', <bit>
  - 'STUFF BIT', None
  - 'EOP', None
+ - 'ERR', None
+ - 'KEEP ALIVE', None
+ - 'RESET', None
 
 <sym>:
  - 'J', 'K', 'SE0', or 'SE1'
 
 <bit>:
- - 0 or 1
+ - '0' or '1'
  - Note: Symbols like SE0, SE1, and the J that's part of EOP don't yield 'BIT'.
 '''
 
@@ -59,20 +62,44 @@ symbols = {
         (0, 1): 'K',
         (1, 1): 'SE1',
     },
+    'automatic': {
+        # (<dp>, <dm>): <symbol/state>
+        (0, 0): 'SE0',
+        (1, 0): 'FS_J',
+        (0, 1): 'LS_J',
+        (1, 1): 'SE1',
+    },
+    # After a PREamble PID, the bus segment between Host and Hub uses LS
+    # signalling rate and FS signalling polarity (USB 2.0 spec, 11.8.4: "For
+    # both upstream and downstream low-speed data, the hub is responsible for
+    # inverting the polarity of the data before transmitting to/from a
+    # low-speed port.").
+    'low-speed-rp': {
+        # (<dp>, <dm>): <symbol/state>
+        (0, 0): 'SE0',
+        (1, 0): 'J',
+        (0, 1): 'K',
+        (1, 1): 'SE1',
+    },
 }
 
 bitrates = {
-    'low-speed': 1500000,   # 1.5Mb/s (+/- 1.5%)
+    'low-speed': 1500000, # 1.5Mb/s (+/- 1.5%)
+    'low-speed-rp': 1500000, # 1.5Mb/s (+/- 1.5%)
     'full-speed': 12000000, # 12Mb/s (+/- 0.25%)
+    'automatic': None
 }
 
-sym_idx = {
-    'J': 0,
-    'K': 1,
-    'SE0': 2,
-    'SE1': 3,
+sym_annotation = {
+    'J': [0, ['J']],
+    'K': [1, ['K']],
+    'SE0': [2, ['SE0', '0']],
+    'SE1': [3, ['SE1', '1']],
 }
 
+class SamplerateError(Exception):
+    pass
+
 class Decoder(srd.Decoder):
     api_version = 2
     id = 'usb_signalling'
@@ -88,7 +115,7 @@ class Decoder(srd.Decoder):
     )
     options = (
         {'id': 'signalling', 'desc': 'Signalling',
-            'default': 'full-speed', 'values': ('full-speed', 'low-speed')},
+            'default': 'automatic', 'values': ('automatic', 'full-speed', 'low-speed')},
     )
     annotations = (
         ('sym-j', 'J symbol'),
@@ -99,26 +126,31 @@ class Decoder(srd.Decoder):
         ('eop', 'End of packet (EOP)'),
         ('bit', 'Bit'),
         ('stuffbit', 'Stuff bit'),
+        ('error', 'Error'),
+        ('keep-alive', 'Low-speed keep-alive'),
+        ('reset', 'Reset'),
     )
     annotation_rows = (
-        ('bits', 'Bits', (4, 5, 6, 7)),
+        ('bits', 'Bits', (4, 5, 6, 7, 8, 9, 10)),
         ('symbols', 'Symbols', (0, 1, 2, 3)),
     )
 
     def __init__(self):
         self.samplerate = None
         self.oldsym = 'J' # The "idle" state is J.
-        self.ss_sop = None
         self.ss_block = None
         self.samplenum = 0
-        self.syms = []
         self.bitrate = None
         self.bitwidth = None
-        self.bitnum = 0
+        self.samplepos = None
         self.samplenum_target = None
+        self.samplenum_edge = None
+        self.samplenum_lastedge = 0
         self.oldpins = None
+        self.edgepins = None
         self.consecutive_ones = 0
-        self.state = 'IDLE'
+        self.bits = None
+        self.state = 'INIT'
 
     def start(self):
         self.out_python = self.register(srd.OUTPUT_PYTHON)
@@ -127,60 +159,72 @@ class Decoder(srd.Decoder):
     def metadata(self, key, value):
         if key == srd.SRD_CONF_SAMPLERATE:
             self.samplerate = value
-            self.bitrate = bitrates[self.options['signalling']]
-            self.bitwidth = float(self.samplerate) / float(self.bitrate)
-            self.halfbit = int(self.bitwidth / 2)
+            self.signalling = self.options['signalling']
+            if self.signalling != 'automatic':
+                self.update_bitrate()
+
+    def update_bitrate(self):
+        self.bitrate = bitrates[self.signalling]
+        self.bitwidth = float(self.samplerate) / float(self.bitrate)
 
     def putpx(self, data):
-        self.put(self.samplenum, self.samplenum, self.out_python, data)
+        s = self.samplenum_edge
+        self.put(s, s, self.out_python, data)
 
     def putx(self, data):
-        self.put(self.samplenum, self.samplenum, self.out_ann, data)
+        s = self.samplenum_edge
+        self.put(s, s, self.out_ann, data)
 
     def putpm(self, data):
-        s, h = self.samplenum, self.halfbit
-        self.put(self.ss_block - h, s + h, self.out_python, data)
+        e = self.samplenum_edge
+        self.put(self.ss_block, e, self.out_python, data)
 
     def putm(self, data):
-        s, h = self.samplenum, self.halfbit
-        self.put(self.ss_block - h, s + h, self.out_ann, data)
+        e = self.samplenum_edge
+        self.put(self.ss_block, e, self.out_ann, data)
 
     def putpb(self, data):
-        s, h = self.samplenum, self.halfbit
-        self.put(s - h, s + h, self.out_python, data)
+        s, e = self.samplenum_lastedge, self.samplenum_edge
+        self.put(s, e, self.out_python, data)
 
     def putb(self, data):
-        s, h = self.samplenum, self.halfbit
-        self.put(s - h, s + h, self.out_ann, data)
+        s, e = self.samplenum_lastedge, self.samplenum_edge
+        self.put(s, e, self.out_ann, data)
 
     def set_new_target_samplenum(self):
-        bitpos = self.ss_sop + (self.bitwidth / 2)
-        bitpos += self.bitnum * self.bitwidth
-        self.samplenum_target = int(bitpos)
+        self.samplepos += self.bitwidth;
+        self.samplenum_target = int(self.samplepos)
+        self.samplenum_lastedge = self.samplenum_edge
+        self.samplenum_edge = int(self.samplepos - (self.bitwidth / 2))
 
     def wait_for_sop(self, sym):
         # Wait for a Start of Packet (SOP), i.e. a J->K symbol change.
-        if sym != 'K':
-            self.oldsym = sym
+        if sym != 'K' or self.oldsym != 'J':
             return
-        self.ss_sop = self.samplenum
+        self.consecutive_ones = 0
+        self.bits = ''
+        self.update_bitrate()
+        self.samplepos = self.samplenum - (self.bitwidth / 2) + 0.5
         self.set_new_target_samplenum()
         self.putpx(['SOP', None])
         self.putx([4, ['SOP', 'S']])
         self.state = 'GET BIT'
 
-    def handle_bit(self, sym, b):
-        if self.consecutive_ones == 6 and b == '0':
-            # Stuff bit.
-            self.putpb(['STUFF BIT', None])
-            self.putb([7, ['Stuff bit: %s' % b, 'SB: %s' % b, '%s' % b]])
-            self.putb([sym_idx[sym], ['%s' % sym]])
-            self.consecutive_ones = 0
+    def handle_bit(self, b):
+        if self.consecutive_ones == 6:
+            if b == '0':
+                # Stuff bit.
+                self.putpb(['STUFF BIT', None])
+                self.putb([7, ['Stuff bit: 0', 'SB: 0', '0']])
+                self.consecutive_ones = 0
+            else:
+                self.putpb(['ERR', None])
+                self.putb([8, ['Bit stuff error', 'BS ERR', 'B']])
+                self.state = 'IDLE'
         else:
             # Normal bit (not a stuff bit).
             self.putpb(['BIT', b])
             self.putb([6, ['%s' % b]])
-            self.putb([sym_idx[sym], ['%s' % sym]])
             if b == '1':
                 self.consecutive_ones += 1
             else:
@@ -188,37 +232,76 @@ class Decoder(srd.Decoder):
 
     def get_eop(self, sym):
         # EOP: SE0 for >= 1 bittime (usually 2 bittimes), then J.
-        self.syms.append(sym)
-        self.putpb(['SYM', sym])
-        self.putb([sym_idx[sym], ['%s' % sym, '%s' % sym[0]]])
-        self.bitnum += 1
         self.set_new_target_samplenum()
+        self.putpb(['SYM', sym])
+        self.putb(sym_annotation[sym])
         self.oldsym = sym
-        if self.syms[-2:] == ['SE0', 'J']:
+        if sym == 'SE0':
+            pass
+        elif sym == 'J':
             # Got an EOP.
             self.putpm(['EOP', None])
             self.putm([5, ['EOP', 'E']])
-            self.bitnum, self.syms, self.state = 0, [], 'IDLE'
-            self.consecutive_ones = 0
+            self.state = 'WAIT IDLE'
+        else:
+            self.putpm(['ERR', None])
+            self.putm([8, ['EOP Error', 'EErr', 'E']])
+            self.state = 'IDLE'
 
     def get_bit(self, sym):
+        self.set_new_target_samplenum()
+        b = '0' if self.oldsym != sym else '1'
+        self.oldsym = sym
         if sym == 'SE0':
-            # Start of an EOP. Change state, run get_eop() for this bit.
+            # Start of an EOP. Change state, save edge
             self.state = 'GET EOP'
-            self.ss_block = self.samplenum
-            self.get_eop(sym)
-            return
-        self.syms.append(sym)
+            self.ss_block = self.samplenum_lastedge
+        else:
+            self.handle_bit(b)
         self.putpb(['SYM', sym])
-        b = '0' if self.oldsym != sym else '1'
-        self.handle_bit(sym, b)
-        self.bitnum += 1
-        self.set_new_target_samplenum()
-        self.oldsym = sym
+        self.putb(sym_annotation[sym])
+        if len(self.bits) <= 16:
+            self.bits += b
+        if len(self.bits) == 16 and self.bits == '0000000100111100':
+            # Sync and low-speed PREamble seen
+            self.putpx(['EOP', None])
+            self.state = 'IDLE'
+            self.signalling = 'low-speed-rp'
+            self.update_bitrate()
+            self.oldsym = 'J'
+        if b == '0':
+            edgesym = symbols[self.signalling][tuple(self.edgepins)]
+            if edgesym not in ('SE0', 'SE1'):
+                if edgesym == sym:
+                    self.bitwidth = self.bitwidth - (0.001 * self.bitwidth)
+                    self.samplepos = self.samplepos - (0.01 * self.bitwidth)
+                else:
+                    self.bitwidth = self.bitwidth + (0.001 * self.bitwidth)
+                    self.samplepos = self.samplepos + (0.01 * self.bitwidth)
+
+    def handle_idle(self, sym):
+        self.samplenum_edge = self.samplenum
+        se0_length = float(self.samplenum - self.samplenum_lastedge) / self.samplerate
+        if se0_length > 2.5e-6: # 2.5us
+            self.putpb(['RESET', None])
+            self.putb([10, ['Reset', 'Res', 'R']])
+            self.signalling = self.options['signalling']
+        elif se0_length > 1.2e-6 and self.signalling == 'low-speed':
+            self.putpb(['KEEP ALIVE', None])
+            self.putb([9, ['Keep-alive', 'KA', 'A']])
+
+        if sym == 'FS_J':
+            self.signalling = 'full-speed'
+            self.update_bitrate()
+        elif sym == 'LS_J':
+            self.signalling = 'low-speed'
+            self.update_bitrate()
+        self.oldsym = 'J'
+        self.state = 'IDLE'
 
     def decode(self, ss, es, data):
-        if self.samplerate is None:
-            raise Exception("Cannot decode without samplerate.")
+        if not self.samplerate:
+            raise SamplerateError('Cannot decode without samplerate.')
         for (self.samplenum, pins) in data:
             # State machine.
             if self.state == 'IDLE':
@@ -226,17 +309,37 @@ class Decoder(srd.Decoder):
                 if self.oldpins == pins:
                     continue
                 self.oldpins = pins
-                sym = symbols[self.options['signalling']][tuple(pins)]
-                self.wait_for_sop(sym)
+                sym = symbols[self.signalling][tuple(pins)]
+                if sym == 'SE0':
+                    self.samplenum_lastedge = self.samplenum
+                    self.state = 'WAIT IDLE'
+                else:
+                    self.wait_for_sop(sym)
+                self.edgepins = pins
             elif self.state in ('GET BIT', 'GET EOP'):
                 # Wait until we're in the middle of the desired bit.
+                if self.samplenum == self.samplenum_edge:
+                    self.edgepins = pins
                 if self.samplenum < self.samplenum_target:
                     continue
-                sym = symbols[self.options['signalling']][tuple(pins)]
+                sym = symbols[self.signalling][tuple(pins)]
                 if self.state == 'GET BIT':
                     self.get_bit(sym)
                 elif self.state == 'GET EOP':
                     self.get_eop(sym)
-            else:
-                raise Exception('Invalid state: %s' % self.state)
-
+                self.oldpins = pins
+            elif self.state == 'WAIT IDLE':
+                if tuple(pins) == (0, 0):
+                    continue
+                if self.samplenum - self.samplenum_lastedge > 1:
+                    sym = symbols[self.options['signalling']][tuple(pins)]
+                    self.handle_idle(sym)
+                else:
+                    sym = symbols[self.signalling][tuple(pins)]
+                    self.wait_for_sop(sym)
+                self.oldpins = pins
+                self.edgepins = pins
+            elif self.state == 'INIT':
+                sym = symbols[self.options['signalling']][tuple(pins)]
+                self.handle_idle(sym)
+                self.oldpins = pins
diff --git a/decoders/dcf77/__init__.py b/decoders/wiegand/__init__.py
similarity index 74%
copy from decoders/dcf77/__init__.py
copy to decoders/wiegand/__init__.py
index 04805c2..20f51f8 100644
--- a/decoders/dcf77/__init__.py
+++ b/decoders/wiegand/__init__.py
@@ -1,7 +1,7 @@
 ##
 ## This file is part of the libsigrokdecode project.
 ##
-## Copyright (C) 2012 Uwe Hermann <uwe at hermann-uwe.de>
+## Copyright (C) 2016 Sean Burford <sburford at google.com>
 ##
 ## 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
@@ -19,12 +19,11 @@
 ##
 
 '''
-This PD decodes the DCF77 protocol (a European long-wave time signal that
-uses a 77.5kHz carrier frequency).
+The Wiegand interface is a de facto wiring standard commonly used to connect
+a card swipe mechanism to the rest of an electronic entry system.
 
 Details:
-http://en.wikipedia.org/wiki/DCF77
+https://en.wikipedia.org/wiki/Wiegand_interface
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/wiegand/pd.py b/decoders/wiegand/pd.py
new file mode 100644
index 0000000..a42c9d2
--- /dev/null
+++ b/decoders/wiegand/pd.py
@@ -0,0 +1,134 @@
+##
+## This file is part of the libsigrokdecode project.
+##
+## Copyright (C) 2016 Sean Burford <sburford at google.com>
+##
+## 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+##
+
+import sigrokdecode as srd
+
+class Decoder(srd.Decoder):
+    api_version = 2
+    id = 'wiegand'
+    name = 'Wiegand'
+    longname = 'Wiegand interface'
+    desc = 'Wiegand interface for electronic entry systems.'
+    license = 'gplv2+'
+    inputs = ['logic']
+    outputs = ['wiegand']
+    channels = (
+        {'id': 'd0', 'name': 'D0', 'desc': 'Data 0 line'},
+        {'id': 'd1', 'name': 'D1', 'desc': 'Data 1 line'},
+    )
+    options = (
+        {'id': 'active', 'desc': 'Data lines active level',
+         'default': 'low', 'values': ('low', 'high')},
+        {'id': 'bitwidth_ms', 'desc': 'Single bit width in milliseconds',
+         'default': 4, 'values': (1, 2, 4, 8, 16, 32)},
+    )
+    annotations = (
+        ('bits', 'Bits'),
+        ('state', 'State'),
+    )
+    annotation_rows = (
+        ('bits', 'Binary value', (0,)),
+        ('state', 'Stream state', (1,)),
+    )
+
+    def __init__(self):
+        self._samples_per_bit = 10
+
+        self._d0_prev = None
+        self._d1_prev = None
+
+        self._state = None
+        self.ss_state = None
+
+        self.ss_bit = None
+        self.es_bit = None
+        self._bit = None
+        self._bits = []
+
+    def start(self):
+        'Register output types and verify user supplied decoder values.'
+        self.out_ann = self.register(srd.OUTPUT_ANN)
+        self._active = self.options['active'] == 'high' and 1 or 0
+        self._inactive = 1 - self._active
+
+    def metadata(self, key, value):
+        'Receive decoder metadata about the data stream.'
+        if key == srd.SRD_CONF_SAMPLERATE:
+            ms_per_sample = 1000 * (1.0 / value)
+            ms_per_bit = float(self.options['bitwidth_ms'])
+            self._samples_per_bit = int(max(1, int(ms_per_bit / ms_per_sample)))
+
+    def _update_state(self, state, bit=None):
+        'Update state and bit values when they change.'
+        if self._bit is not None:
+            self._bits.append(self._bit)
+            self.put(self.ss_bit, self.samplenum, self.out_ann,
+                     [0, [str(self._bit)]])
+        self._bit = bit
+        self.ss_bit = self.samplenum
+        if bit is not None:
+            # Set a timeout so that the final bit ends.
+            self.es_bit = self.samplenum + self._samples_per_bit
+        else:
+            self.es_bit = None
+
+        if state != self._state:
+            ann = None
+            if self._state == 'data':
+                accum_bits = ''.join(str(x) for x in self._bits)
+                ann = [1, ['%d bits %s' % (len(self._bits), accum_bits),
+                           '%d bits' % len(self._bits)]]
+            elif self._state == 'invalid':
+                ann = [1, [self._state]]
+            if ann:
+                self.put(self.ss_state, self.samplenum, self.out_ann, ann)
+            self.ss_state = self.samplenum
+            self._state = state
+            self._bits = []
+
+    def decode(self, ss, es, data):
+        for self.samplenum, (d0, d1) in data:
+            if d0 == self._d0_prev and d1 == self._d1_prev:
+                if self.es_bit and self.samplenum >= self.es_bit:
+                    if (d0, d1) == (self._inactive, self._inactive):
+                        self._update_state('idle')
+                    else:
+                        self._update_state('invalid')
+                continue
+
+            if self._state in (None, 'idle', 'data'):
+                if (d0, d1) == (self._active, self._inactive):
+                    self._update_state('data', 0)
+                elif (d0, d1) == (self._inactive, self._active):
+                    self._update_state('data', 1)
+                elif (d0, d1) == (self._active, self._active):
+                    self._update_state('invalid')
+            elif self._state == 'invalid':
+                # Wait until we see an idle state before leaving invalid.
+                # This prevents inverted lines from being misread.
+                if (d0, d1) == (self._inactive, self._inactive):
+                    self._update_state('idle')
+
+            self._d0_prev, self._d1_prev = d0, d1
+
+    def report(self):
+        return '%s: %s D0 %d D1 %d (active on %d), %d samples per bit' % (
+            self.name, self._state, self._d0_prev, self._d1_prev,
+            self._active, self._samples_per_bit)
diff --git a/decoders/xfp/__init__.py b/decoders/xfp/__init__.py
index fa4e8a2..51936e5 100644
--- a/decoders/xfp/__init__.py
+++ b/decoders/xfp/__init__.py
@@ -37,5 +37,4 @@ The XFP specification is available here:
   ftp://ftp.seagate.com/sff/INF-8077.PDF
 '''
 
-from .pd import *
-
+from .pd import Decoder
diff --git a/decoders/xfp/pd.py b/decoders/xfp/pd.py
index b8ec8ed..27135e5 100644
--- a/decoders/xfp/pd.py
+++ b/decoders/xfp/pd.py
@@ -18,177 +18,9 @@
 ##
 
 import sigrokdecode as srd
-
-MODULE_ID = {
-    0x01: 'GBIC',
-    0x02: 'Integrated module/connector',
-    0x03: 'SFP',
-    0x04: '300-pin XBI',
-    0x05: 'XENPAK',
-    0x06: 'XFP',
-    0x07: 'XFF',
-    0x08: 'XFP-E',
-    0x09: 'XPAK',
-    0x0a: 'X2',
-}
-
-ALARM_THRESHOLDS = {
-    0:  "Temp high alarm",
-    2:  "Temp low alarm",
-    4:  "Temp high warning",
-    6:  "Temp low warning",
-    16: "Bias high alarm",
-    18: "Bias low alarm",
-    20: "Bias high warning",
-    22: "Bias low warning",
-    24: "TX power high alarm",
-    26: "TX power low alarm",
-    28: "TX power high warning",
-    30: "TX power low warning",
-    32: "RX power high alarm",
-    34: "RX power low alarm",
-    36: "RX power high warning",
-    38: "RX power low warning",
-    40: "AUX 1 high alarm",
-    42: "AUX 1 low alarm",
-    44: "AUX 1 high warning",
-    46: "AUX 1 low warning",
-    48: "AUX 2 high alarm",
-    50: "AUX 2 low alarm",
-    52: "AUX 2 high warning",
-    54: "AUX 2 low warning",
-}
-
-AD_READOUTS = {
-    0:  "Module temperature",
-    4:  "TX bias current",
-    6:  "Measured TX output power",
-    8:  "Measured RX input power",
-    10: "AUX 1 measurement",
-    12: "AUX 2 measurement",
-}
-
-GCS_BITS = [
-    "TX disable",
-    "Soft TX disable",
-    "MOD_NR",
-    "P_Down",
-    "Soft P_Down",
-    "Interrupt",
-    "RX_LOS",
-    "Data_Not_Ready",
-    "TX_NR",
-    "TX_Fault",
-    "TX_CDR not locked",
-    "RX_NR",
-    "RX_CDR not locked",
-]
-
-CONNECTOR = {
-    0x01:   "SC",
-    0x02:   "Fibre Channel style 1 copper",
-    0x03:   "Fibre Channel style 2 copper",
-    0x04:   "BNC/TNC",
-    0x05:   "Fibre Channel coax",
-    0x06:   "FiberJack",
-    0x07:   "LC",
-    0x08:   "MT-RJ",
-    0x09:   "MU",
-    0x0a:   "SG",
-    0x0b:   "Optical pigtail",
-    0x20:   "HSSDC II",
-    0x21:   "Copper pigtail",
-}
-
-TRANSCEIVER = [
-    # 10GB Ethernet
-    ["10GBASE-SR", "10GBASE-LR", "10GBASE-ER", "10GBASE-LRM", "10GBASE-SW",
-        "10GBASE-LW",   "10GBASE-EW"],
-    # 10GB Fibre Channel
-    ["1200-MX-SN-I", "1200-SM-LL-L", "Extended Reach 1550 nm",
-        "Intermediate reach 1300 nm FP"],
-    # 10GB Copper
-    [],
-    # 10GB low speed
-    ["1000BASE-SX / 1xFC MMF", "1000BASE-LX / 1xFC SMF", "2xFC MMF",
-        "2xFC SMF", "OC48-SR", "OC48-IR", "OC48-LR"],
-    # 10GB SONET/SDH interconnect
-    ["I-64.1r", "I-64.1", "I-64.2r", "I-64.2", "I-64.3", "I-64.5"],
-    # 10GB SONET/SDH short haul
-    ["S-64.1", "S-64.2a", "S-64.2b", "S-64.3a", "S-64.3b", "S-64.5a", "S-64.5b"],
-    # 10GB SONET/SDH long haul
-    ["L-64.1", "L-64.2a", "L-64.2b", "L-64.2c", "L-64.3", "G.959.1 P1L1-2D2"],
-    # 10GB SONET/SDH very long haul
-    ["V-64.2a", "V-64.2b", "V-64.3"],
-]
-
-SERIAL_ENCODING = [
-    "64B/66B",
-    "8B/10B",
-    "SONET scrambled",
-    "NRZ",
-    "RZ",
-]
-
-XMIT_TECH = [
-    "850 nm VCSEL",
-    "1310 nm VCSEL",
-    "1550 nm VCSEL",
-    "1310 nm FP",
-    "1310 nm DFB",
-    "1550 nm DFB",
-    "1310 nm EML"
-    "1550 nm EML"
-    "copper",
-]
-
-CDR = [
-    "9.95Gb/s",
-    "10.3Gb/s",
-    "10.5Gb/s",
-    "10.7Gb/s",
-    "11.1Gb/s",
-    "(unknown)",
-    "lineside loopback mode",
-    "XFI loopback mode",
-]
-
-DEVICE_TECH = [
-    ["no wavelength control", "sctive wavelength control"],
-    ["uncooled transmitter device", "cooled transmitter"],
-    ["PIN detector", "APD detector"],
-    ["transmitter not tunable", "transmitter tunable"],
-]
-
-ENHANCED_OPTS = [
-    "VPS",
-    "soft TX_DISABLE",
-    "soft P_Down",
-    "VPS LV regulator mode",
-    "VPS bypassed regulator mode",
-    "active FEC control",
-    "wavelength tunability",
-    "CMU",
-]
-
-AUX_TYPES = [
-    "not implemented",
-    "APD bias voltage",
-    "(unknown)",
-    "TEC current",
-    "laser temperature",
-    "laser wavelength",
-    "5V supply voltage",
-    "3.3V supply voltage",
-    "1.8V supply voltage",
-    "-5.2V supply voltage",
-    "5V supply current",
-    "(unknown)",
-    "(unknown)",
-    "3.3V supply current",
-    "1.8V supply current",
-    "-5.2V supply current",
-]
+from common.plugtrx import (MODULE_ID, ALARM_THRESHOLDS, AD_READOUTS, GCS_BITS,
+        CONNECTOR, TRANSCEIVER, SERIAL_ENCODING, XMIT_TECH, CDR, DEVICE_TECH,
+        ENHANCED_OPTS, AUX_TYPES)
 
 class Decoder(srd.Decoder):
     api_version = 2
@@ -204,7 +36,7 @@ class Decoder(srd.Decoder):
         ('fields', 'XFP structure fields'),
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         # Received data items, used as an index into samplenum/data
         self.cnt = -1
         # Start/end sample numbers per data item
@@ -318,7 +150,7 @@ class Decoder(srd.Decoder):
                 self.annotate("Vendor ID", chr(data[i]), cnt, cnt)
 
     # Convert 16-bit two's complement values, with each increment
-    # representing 1/256C, to degrees Celcius.
+    # representing 1/256C, to degrees Celsius.
     def to_temp(self, value):
         if value & 0x8000:
             value = -((value ^ 0xffff) + 1)
@@ -644,4 +476,3 @@ class Decoder(srd.Decoder):
         self.annotate("AUX1 monitoring", aux)
         aux = AUX_TYPES[data[0] & 0x0f]
         self.annotate("AUX2 monitoring", aux)
-
diff --git a/decoders/z80/pd.py b/decoders/z80/pd.py
index e0d7ae4..a8acf53 100644
--- a/decoders/z80/pd.py
+++ b/decoders/z80/pd.py
@@ -110,7 +110,7 @@ class Decoder(srd.Decoder):
         ('warnings', 'Warnings', (Ann.WARN,))
     )
 
-    def __init__(self, **kwargs):
+    def __init__(self):
         self.prev_cycle = Cycle.NONE
         self.op_state   = self.state_IDLE
 
diff --git a/error.c b/error.c
index e6abd4b..f31f196 100644
--- a/error.c
+++ b/error.c
@@ -18,6 +18,7 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
+#include <config.h>
 #include "libsigrokdecode.h"
 
 /**
diff --git a/exception.c b/exception.c
index 1ce66a8..7027df5 100644
--- a/exception.c
+++ b/exception.c
@@ -17,75 +17,139 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <stdarg.h>
 #include <glib.h>
-#include <frameobject.h> /* Python header not pulled in by default. */
+
+static char *py_stringify(PyObject *py_obj)
+{
+	PyObject *py_str, *py_bytes;
+	char *str = NULL;
+
+	if (!py_obj)
+		return NULL;
+
+	py_str = PyObject_Str(py_obj);
+	if (!py_str || !PyUnicode_Check(py_str))
+		goto cleanup;
+
+	py_bytes = PyUnicode_AsUTF8String(py_str);
+	if (!py_bytes)
+		goto cleanup;
+
+	str = g_strdup(PyBytes_AsString(py_bytes));
+	Py_DECREF(py_bytes);
+
+cleanup:
+	Py_XDECREF(py_str);
+	if (!str) {
+		PyErr_Clear();
+		srd_dbg("Failed to stringify object.");
+	}
+	return str;
+}
+
+static char *py_get_string_attr(PyObject *py_obj, const char *attr)
+{
+	PyObject *py_str, *py_bytes;
+	char *str = NULL;
+
+	if (!py_obj)
+		return NULL;
+
+	py_str = PyObject_GetAttrString(py_obj, attr);
+	if (!py_str || !PyUnicode_Check(py_str))
+		goto cleanup;
+
+	py_bytes = PyUnicode_AsUTF8String(py_str);
+	if (!py_bytes)
+		goto cleanup;
+
+	str = g_strdup(PyBytes_AsString(py_bytes));
+	Py_DECREF(py_bytes);
+
+cleanup:
+	Py_XDECREF(py_str);
+	if (!str) {
+		PyErr_Clear();
+		srd_dbg("Failed to get object attribute %s.", attr);
+	}
+	return str;
+}
 
 /** @private */
 SRD_PRIV void srd_exception_catch(const char *format, ...)
 {
-	PyObject *etype, *evalue, *etb, *py_str;
-	PyTracebackObject *py_tb;
-	GString *msg;
 	va_list args;
-	char *ename, *str, *tracestr;
+	PyObject *py_etype, *py_evalue, *py_etraceback;
+	PyObject *py_mod, *py_func, *py_tracefmt;
+	char *msg, *etype_name, *evalue_str, *tracefmt_str;
+	const char *etype_name_fallback;
 
-	if (!PyErr_Occurred())
-		/* Nothing is wrong. */
-		return;
+	py_etype = py_evalue = py_etraceback = py_mod = py_func = NULL;
 
-	PyErr_Fetch(&etype, &evalue, &etb);
-	PyErr_NormalizeException(&etype, &evalue, &etb);
+	va_start(args, format);
+	msg = g_strdup_vprintf(format, args);
+	va_end(args);
 
-	if (!(py_str = PyObject_Str(evalue))) {
-		/* Shouldn't happen. */
-		srd_dbg("Failed to convert exception value to string.");
-		return;
+	PyErr_Fetch(&py_etype, &py_evalue, &py_etraceback);
+	if (!py_etype) {
+		/* No current exception, so just print the message. */
+		srd_err("%s.", msg);
+		goto cleanup;
 	}
+	PyErr_NormalizeException(&py_etype, &py_evalue, &py_etraceback);
 
-	msg = g_string_sized_new(128);
-	va_start(args, format);
-	g_string_vprintf(msg, format, args);
-	va_end(args);
+	etype_name = py_get_string_attr(py_etype, "__name__");
+	evalue_str = py_stringify(py_evalue);
+	etype_name_fallback = (etype_name) ? etype_name : "(unknown exception)";
 
-	/* Can be NULL. */
-	if (evalue)
-		ename = (char *)Py_TYPE(evalue)->tp_name;
+	if (evalue_str)
+		srd_err("%s: %s: %s", etype_name_fallback, msg, evalue_str);
 	else
-		ename = "(unknown exception)";
-
-	/* Send the exception error message(s) to srd_err(). */
-	py_str_as_str(py_str, &str);
-	g_string_append(msg, ename);
-	g_string_append(msg, ": ");
-	g_string_append(msg, str);
-	Py_DecRef(py_str);
-	srd_err(msg->str);
-
-	/* Send a more precise error location to srd_dbg(), if we have it. */
-	if (etb && etb != Py_None) {
-		tracestr = NULL;
-		py_tb = (PyTracebackObject *)etb;
-		py_str = PyUnicode_FromFormat("%U:%d in %U",
-					py_tb->tb_frame->f_code->co_filename,
-					py_tb->tb_frame->f_lineno,
-					py_tb->tb_frame->f_code->co_name);
-		py_str_as_str(py_str, &tracestr);
-		Py_DecRef(py_str);
-		g_string_printf(msg, "%s in %s: %s", ename, tracestr, str);
-		srd_dbg(msg->str);
-		g_free(tracestr);
+		srd_err("%s: %s.", etype_name_fallback, msg);
+
+	g_free(evalue_str);
+	g_free(etype_name);
+
+	/* If there is no traceback object, we are done. */
+	if (!py_etraceback)
+		goto cleanup;
+
+	py_mod = py_import_by_name("traceback");
+	if (!py_mod)
+		goto cleanup;
+
+	py_func = PyObject_GetAttrString(py_mod, "format_exception");
+	if (!py_func || !PyCallable_Check(py_func))
+		goto cleanup;
+
+	/* Call into Python to format the stack trace. */
+	py_tracefmt = PyObject_CallFunctionObjArgs(py_func,
+			py_etype, py_evalue, py_etraceback, NULL);
+	if (!py_tracefmt)
+		goto cleanup;
+
+	tracefmt_str = py_stringify(py_tracefmt);
+	Py_DECREF(py_tracefmt);
+
+	/* Log the detailed stack trace. */
+	if (tracefmt_str) {
+		srd_dbg("%s", tracefmt_str);
+		g_free(tracefmt_str);
 	}
-	g_free(str);
-	g_string_free(msg, TRUE);
 
-	Py_XDECREF(etype);
-	Py_XDECREF(evalue);
-	Py_XDECREF(etb);
+cleanup:
+	Py_XDECREF(py_func);
+	Py_XDECREF(py_mod);
+	Py_XDECREF(py_etraceback);
+	Py_XDECREF(py_evalue);
+	Py_XDECREF(py_etype);
 
 	/* Just in case. */
 	PyErr_Clear();
+
+	g_free(msg);
 }
diff --git a/instance.c b/instance.c
index 8a5ddef..e4cf0bf 100644
--- a/instance.c
+++ b/instance.c
@@ -18,9 +18,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <glib.h>
 #include <inttypes.h>
 #include <stdlib.h>
@@ -30,8 +30,8 @@
 
 extern SRD_PRIV GSList *sessions;
 
-/* type_logic.c */
-extern SRD_PRIV PyTypeObject srd_logic_type;
+/* module_sigrokdecode.c */
+extern SRD_PRIV PyObject *srd_logic_type;
 
 /** @endcond */
 
@@ -64,11 +64,11 @@ extern SRD_PRIV PyTypeObject srd_logic_type;
 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
 		GHashTable *options)
 {
-    struct srd_decoder_option *sdo;
+	struct srd_decoder_option *sdo;
 	PyObject *py_di_options, *py_optval;
 	GVariant *value;
-    GSList *l;
-    double val_double;
+	GSList *l;
+	double val_double;
 	gint64 val_int;
 	int ret;
 	const char *val_str;
@@ -96,7 +96,7 @@ SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
 	}
 
 	ret = SRD_ERR_PYTHON;
-    py_optval = NULL;
+	py_optval = NULL;
 
 	/*
 	 * The 'options' tuple is a class variable, but we need to
@@ -110,59 +110,60 @@ SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
 	py_di_options = PyDict_New();
 	PyObject_SetAttrString(di->py_inst, "options", py_di_options);
 
-    for (l = di->decoder->options; l; l = l->next) {
-        sdo = l->data;
-        if ((value = g_hash_table_lookup(options, sdo->id))) {
-            /* A value was supplied for this option. */
-            if (!g_variant_type_equal(g_variant_get_type(value),
-                    g_variant_get_type(sdo->def))) {
-                srd_err("Option '%s' should have the same type "
-                        "as the default value.", sdo->id);
-                goto err_out;
-            }
-        } else {
-            /* Use default for this option. */
-            value = sdo->def;
-        }
-        if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
-            val_str = g_variant_get_string(value, NULL);
-            if (!(py_optval = PyUnicode_FromString(val_str))) {
-                /* Some UTF-8 encoding error. */
-                PyErr_Clear();
-                srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
-                goto err_out;
-            }
-        } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
-            val_int = g_variant_get_int64(value);
-            if (!(py_optval = PyLong_FromLong(val_int))) {
-                /* ValueError Exception */
-                PyErr_Clear();
-                srd_err("Option '%s' has invalid integer value.", sdo->id);
-                goto err_out;
-            }
-        } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
-            val_double = g_variant_get_double(value);
-            if (!(py_optval = PyFloat_FromDouble(val_double))) {
-                /* ValueError Exception */
-                PyErr_Clear();
-                srd_err("Option '%s' has invalid float value.", sdo->id);
-                goto err_out;
-            }
-        }
+	for (l = di->decoder->options; l; l = l->next) {
+		sdo = l->data;
+		if ((value = g_hash_table_lookup(options, sdo->id))) {
+			/* A value was supplied for this option. */
+			if (!g_variant_type_equal(g_variant_get_type(value),
+				  g_variant_get_type(sdo->def))) {
+				srd_err("Option '%s' should have the same type "
+					"as the default value.", sdo->id);
+				goto err_out;
+			}
+		} else {
+			/* Use default for this option. */
+			value = sdo->def;
+		}
+		if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
+			val_str = g_variant_get_string(value, NULL);
+			if (!(py_optval = PyUnicode_FromString(val_str))) {
+				/* Some UTF-8 encoding error. */
+				PyErr_Clear();
+				srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
+				goto err_out;
+			}
+		} else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
+			val_int = g_variant_get_int64(value);
+			if (!(py_optval = PyLong_FromLong(val_int))) {
+				/* ValueError Exception */
+				PyErr_Clear();
+				srd_err("Option '%s' has invalid integer value.", sdo->id);
+				goto err_out;
+			}
+		} else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
+			val_double = g_variant_get_double(value);
+			if (!(py_optval = PyFloat_FromDouble(val_double))) {
+				/* ValueError Exception */
+				PyErr_Clear();
+				srd_err("Option '%s' has invalid float value.",
+					sdo->id);
+				goto err_out;
+			}
+		}
 		if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
 			goto err_out;
-        /* Not harmful even if we used the default. */
-        g_hash_table_remove(options, sdo->id);
-    }
-    if (g_hash_table_size(options) != 0)
-        srd_warn("Unknown options specified for '%s'", di->inst_id);
+		/* Not harmful even if we used the default. */
+		g_hash_table_remove(options, sdo->id);
+	}
+	if (g_hash_table_size(options) != 0)
+		srd_warn("Unknown options specified for '%s'", di->inst_id);
 
 	ret = SRD_OK;
 
 err_out:
 	Py_XDECREF(py_optval);
 	if (PyErr_Occurred()) {
-		srd_exception_catch("Stray exception in srd_inst_option_set().");
+		srd_exception_catch("Stray exception in srd_inst_option_set()");
 		ret = SRD_ERR_PYTHON;
 	}
 
@@ -186,16 +187,13 @@ static gint compare_channel_id(const struct srd_channel *pdch,
  * @param new_channels A GHashTable of channels to set. Key is channel name,
  *                     value is the channel number. Samples passed to this
  *                     instance will be arranged in this order.
- * @param unit_size Number of bytes per sample in the data stream to be passed
- *                  to the decoder. The highest channel index specified in the
- *                  channel map must lie within a sample unit.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
  *
- * @since 0.3.0
+ * @since 0.4.0
  */
 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
-		GHashTable *new_channels, int unit_size)
+		GHashTable *new_channels)
 {
 	GVariant *channel_val;
 	GList *l;
@@ -204,8 +202,8 @@ SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
 	int *new_channelmap, new_channelnum, num_required_channels, i;
 	char *channel_id;
 
-	srd_dbg("Setting channels for instance %s with list of %d channels, "
-		"unitsize %d.", di->inst_id, g_hash_table_size(new_channels), unit_size);
+	srd_dbg("Setting channels for instance %s with list of %d channels.",
+		di->inst_id, g_hash_table_size(new_channels));
 
 	if (g_hash_table_size(new_channels) == 0)
 		/* No channels provided. */
@@ -218,12 +216,7 @@ SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
 		return SRD_ERR_ARG;
 	}
 
-	new_channelmap = NULL;
-
-	if (!(new_channelmap = g_try_malloc(sizeof(int) * di->dec_num_channels))) {
-		srd_err("Failed to g_malloc() new channel map.");
-		return SRD_ERR_MALLOC;
-	}
+	new_channelmap = g_malloc(sizeof(int) * di->dec_num_channels);
 
 	/*
 	 * For now, map all indexes to channel -1 (can be overridden later).
@@ -243,19 +236,13 @@ SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
 			return SRD_ERR_ARG;
 		}
 		new_channelnum = g_variant_get_int32(channel_val);
-		if (new_channelnum >= 8 * unit_size) {
-			srd_err("Channel index %d not within data unit (%d bit).",
-				new_channelnum, 8 * unit_size);
-			g_free(new_channelmap);
-			return SRD_ERR_ARG;
-		}
 		if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
 				(GCompareFunc)compare_channel_id))) {
 			/* Fall back on optional channels. */
 			if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
-			     channel_id, (GCompareFunc) compare_channel_id))) {
+			     channel_id, (GCompareFunc)compare_channel_id))) {
 				srd_err("Protocol decoder %s has no channel "
-						"'%s'.", di->decoder->name, channel_id);
+					"'%s'.", di->decoder->name, channel_id);
 				g_free(new_channelmap);
 				return SRD_ERR_ARG;
 			}
@@ -265,13 +252,12 @@ SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
 		srd_dbg("Setting channel mapping: %s (index %d) = channel %d.",
 			pdch->id, pdch->order, new_channelnum);
 	}
-	di->data_unitsize = unit_size;
 
 	srd_dbg("Final channel map:");
 	num_required_channels = g_slist_length(di->decoder->channels);
 	for (i = 0; i < di->dec_num_channels; i++) {
 		srd_dbg(" - index %d = channel %d (%s)", i, new_channelmap[i],
-		        (i < num_required_channels) ? "required" : "optional");
+			(i < num_required_channels) ? "required" : "optional");
 	}
 
 	/* Report an error if not all required channels were specified. */
@@ -323,10 +309,7 @@ SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
 		return NULL;
 	}
 
-	if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
-		srd_err("Failed to g_malloc() instance.");
-		return NULL;
-	}
+	di = g_malloc0(sizeof(struct srd_decoder_inst));
 
 	di->decoder = dec;
 	di->sess = sess;
@@ -344,31 +327,21 @@ SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
 	di->dec_num_channels = g_slist_length(di->decoder->channels) +
 			g_slist_length(di->decoder->opt_channels);
 	if (di->dec_num_channels) {
-		if (!(di->dec_channelmap =
-				g_try_malloc(sizeof(int) * di->dec_num_channels))) {
-			srd_err("Failed to g_malloc() channel map.");
-			g_free(di);
-			return NULL;
-		}
+		di->dec_channelmap =
+				g_malloc(sizeof(int) * di->dec_num_channels);
 		for (i = 0; i < di->dec_num_channels; i++)
 			di->dec_channelmap[i] = i;
-		di->data_unitsize = (di->dec_num_channels + 7) / 8;
 		/*
 		 * Will be used to prepare a sample at every iteration
 		 * of the instance's decode() method.
 		 */
-		if (!(di->channel_samples = g_try_malloc(di->dec_num_channels))) {
-			srd_err("Failed to g_malloc() sample buffer.");
-			g_free(di->dec_channelmap);
-			g_free(di);
-			return NULL;
-		}
+		di->channel_samples = g_malloc(di->dec_num_channels);
 	}
 
 	/* Create a new instance of this decoder class. */
 	if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
 		if (PyErr_Occurred())
-			srd_exception_catch("failed to create %s instance: ",
+			srd_exception_catch("Failed to create %s instance",
 					decoder_id);
 		g_free(di->dec_channelmap);
 		g_free(di);
@@ -421,7 +394,7 @@ SRD_API int srd_inst_stack(struct srd_session *sess,
 	/* Stack on top of source di. */
 	di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
 
-	srd_dbg("Stacked %s on top of %s.", di_top->inst_id, di_bottom->inst_id);
+	srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
 
 	return SRD_OK;
 }
@@ -532,7 +505,7 @@ SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
 			di->inst_id);
 
 	if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
-		srd_exception_catch("Protocol decoder instance %s: ",
+		srd_exception_catch("Protocol decoder instance %s",
 				di->inst_id);
 		return SRD_ERR_PYTHON;
 	}
@@ -549,7 +522,7 @@ SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
 }
 
 /**
- * Run the specified decoder function.
+ * Decode a chunk of samples.
  *
  * @param di The decoder instance to call. Must not be NULL.
  * @param start_samplenum The starting sample number for the buffer's sample
@@ -558,23 +531,19 @@ SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
  * 			  set, relative to the start of capture.
  * @param inbuf The buffer to decode. Must not be NULL.
  * @param inbuflen Length of the buffer. Must be > 0.
+ * @param unitsize The number of bytes per sample. Must be > 0.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
  *
  * @private
- *
- * @since 0.1.0
  */
 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
 		uint64_t start_samplenum, uint64_t end_samplenum,
-		const uint8_t *inbuf, uint64_t inbuflen)
+		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
 {
 	PyObject *py_res;
 	srd_logic *logic;
-
-	srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
-		"starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
-		start_samplenum);
+	long apiver;
 
 	/* Return an error upon unusable input. */
 	if (!di) {
@@ -589,28 +558,45 @@ SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
 		srd_dbg("empty buffer");
 		return SRD_ERR_ARG;
 	}
+	if (unitsize == 0) {
+		srd_dbg("unitsize 0");
+		return SRD_ERR_ARG;
+	}
 
-	/*
-	 * Create new srd_logic object. Each iteration around the PD's loop
-	 * will fill one sample into this object.
-	 */
-	logic = PyObject_New(srd_logic, &srd_logic_type);
-	Py_INCREF(logic);
-	logic->di = (struct srd_decoder_inst *)di;
-	logic->start_samplenum = start_samplenum;
-	logic->itercnt = 0;
-	logic->inbuf = (uint8_t *)inbuf;
-	logic->inbuflen = inbuflen;
-	logic->sample = PyList_New(2);
-	Py_INCREF(logic->sample);
-
-	Py_IncRef(di->py_inst);
-	if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
+	((struct srd_decoder_inst *)di)->data_unitsize = unitsize;
+
+	srd_dbg("Decoding: start sample %" PRIu64 ", end sample %"
+		PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
+		"%d), instance %s.", start_samplenum, end_samplenum,
+		end_samplenum - start_samplenum, inbuflen, di->data_unitsize,
+		di->inst_id);
+
+	apiver = srd_decoder_apiver(di->decoder);
+
+	if (apiver == 2) {
+		/*
+		 * Create new srd_logic object. Each iteration around the PD's
+		 * loop will fill one sample into this object.
+		 */
+		logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
+		Py_INCREF(logic);
+		logic->di = (struct srd_decoder_inst *)di;
+		logic->start_samplenum = start_samplenum;
+		logic->itercnt = 0;
+		logic->inbuf = (uint8_t *)inbuf;
+		logic->inbuflen = inbuflen;
+		logic->sample = PyList_New(2);
+		Py_INCREF(logic->sample);
+
+		Py_IncRef(di->py_inst);
+		if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
 			"KKO", start_samplenum, end_samplenum, logic))) {
-		srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
-		return SRD_ERR_PYTHON;
+			srd_exception_catch("Protocol decoder instance %s",
+					di->inst_id);
+			return SRD_ERR_PYTHON;
+		}
+		Py_DecRef(py_res);
 	}
-	Py_DecRef(py_res);
 
 	return SRD_OK;
 }
@@ -626,6 +612,7 @@ SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
 	Py_DecRef(di->py_inst);
 	g_free(di->inst_id);
 	g_free(di->dec_channelmap);
+	g_free(di->channel_samples);
 	g_slist_free(di->next_di);
 	for (l = di->pd_output; l; l = l->next) {
 		pdo = l->data;
@@ -661,4 +648,3 @@ SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
 }
 
 /** @} */
-
diff --git a/libsigrokdecode-internal.h b/libsigrokdecode-internal.h
index f386cd7..8259b97 100644
--- a/libsigrokdecode-internal.h
+++ b/libsigrokdecode-internal.h
@@ -22,8 +22,24 @@
 #ifndef LIBSIGROKDECODE_LIBSIGROKDECODE_INTERNAL_H
 #define LIBSIGROKDECODE_LIBSIGROKDECODE_INTERNAL_H
 
+/* Use the stable ABI subset as per PEP 384. */
+#define Py_LIMITED_API 0x03020000
+
+#include <Python.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
 #include "libsigrokdecode.h"
 
+/* Custom Python types: */
+
+typedef struct {
+	PyObject_HEAD
+	struct srd_decoder_inst *di;
+	uint64_t start_samplenum;
+	unsigned int itercnt;
+	uint8_t *inbuf;
+	uint64_t inbuflen;
+	PyObject *sample;
+} srd_logic;
+
 struct srd_session {
 	int session_id;
 
@@ -34,7 +50,6 @@ struct srd_session {
 	GSList *callbacks;
 };
 
-
 /* srd.c */
 SRD_PRIV int srd_decoder_searchpath_add(const char *path);
 
@@ -49,30 +64,58 @@ SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj( const GSList *stack,
 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di);
 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
 		uint64_t start_samplenum, uint64_t end_samplenum,
-		const uint8_t *inbuf, uint64_t inbuflen);
+		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize);
 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di);
 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack);
 
 /* log.c */
-SRD_PRIV int srd_log(int loglevel, const char *format, ...);
-SRD_PRIV int srd_spew(const char *format, ...);
-SRD_PRIV int srd_dbg(const char *format, ...);
-SRD_PRIV int srd_info(const char *format, ...);
-SRD_PRIV int srd_warn(const char *format, ...);
-SRD_PRIV int srd_err(const char *format, ...);
+#if defined(G_OS_WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+/*
+ * On MinGW, we need to specify the gnu_printf format flavor or GCC
+ * will assume non-standard Microsoft printf syntax.
+ */
+SRD_PRIV int srd_log(int loglevel, const char *format, ...)
+		__attribute__((__format__ (__gnu_printf__, 2, 3)));
+#else
+SRD_PRIV int srd_log(int loglevel, const char *format, ...) G_GNUC_PRINTF(2, 3);
+#endif
+
+#define srd_spew(...)	srd_log(SRD_LOG_SPEW, __VA_ARGS__)
+#define srd_dbg(...)	srd_log(SRD_LOG_DBG,  __VA_ARGS__)
+#define srd_info(...)	srd_log(SRD_LOG_INFO, __VA_ARGS__)
+#define srd_warn(...)	srd_log(SRD_LOG_WARN, __VA_ARGS__)
+#define srd_err(...)	srd_log(SRD_LOG_ERR,  __VA_ARGS__)
+
+/* decoder.c */
+SRD_PRIV long srd_decoder_apiver(const struct srd_decoder *d);
+
+/* type_decoder.c */
+SRD_PRIV PyObject *srd_Decoder_type_new(void);
+
+/* type_logic.c */
+SRD_PRIV PyObject *srd_logic_type_new(void);
 
 /* module_sigrokdecode.c */
 PyMODINIT_FUNC PyInit_sigrokdecode(void);
 
 /* util.c */
-SRD_PRIV int py_attr_as_str(const PyObject *py_obj, const char *attr,
-        char **outstr);
-SRD_PRIV int py_dictitem_as_str(const PyObject *py_obj, const char *key,
-        char **outstr);
-SRD_PRIV int py_str_as_str(const PyObject *py_str, char **outstr);
-SRD_PRIV int py_strseq_to_char(const PyObject *py_strseq, char ***outstr);
+SRD_PRIV PyObject *py_import_by_name(const char *name);
+SRD_PRIV int py_attr_as_str(PyObject *py_obj, const char *attr, char **outstr);
+SRD_PRIV int py_dictitem_as_str(PyObject *py_obj, const char *key, char **outstr);
+SRD_PRIV int py_str_as_str(PyObject *py_str, char **outstr);
+SRD_PRIV int py_strseq_to_char(PyObject *py_strseq, char ***out_strv);
+SRD_PRIV GVariant *py_obj_to_variant(PyObject *py_obj);
 
 /* exception.c */
-SRD_PRIV void srd_exception_catch(const char *format, ...);
+#if defined(G_OS_WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4))
+/*
+ * On MinGW, we need to specify the gnu_printf format flavor or GCC
+ * will assume non-standard Microsoft printf syntax.
+ */
+SRD_PRIV void srd_exception_catch(const char *format, ...)
+		__attribute__((__format__ (__gnu_printf__, 1, 2)));
+#else
+SRD_PRIV void srd_exception_catch(const char *format, ...) G_GNUC_PRINTF(1, 2);
+#endif
 
 #endif
diff --git a/libsigrokdecode.h b/libsigrokdecode.h
index 9d2dbd3..03a5de0 100644
--- a/libsigrokdecode.h
+++ b/libsigrokdecode.h
@@ -19,10 +19,9 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#ifndef LIBSIGROKDECODE_SIGROKDECODE_H
-#define LIBSIGROKDECODE_SIGROKDECODE_H
+#ifndef LIBSIGROKDECODE_LIBSIGROKDECODE_H
+#define LIBSIGROKDECODE_LIBSIGROKDECODE_H
 
-#include <Python.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
 #include <stdint.h>
 #include <glib.h>
 
@@ -180,14 +179,14 @@ struct srd_decoder {
 	 */
 	GSList *binary;
 
-	/** List of decoder options.  */
+	/** List of decoder options. */
 	GSList *options;
 
 	/** Python module. */
-	PyObject *py_mod;
+	void *py_mod;
 
 	/** sigrokdecode.Decoder class. */
-	PyObject *py_dec;
+	void *py_dec;
 };
 
 /**
@@ -209,7 +208,7 @@ struct srd_decoder_option {
 	char *id;
 	char *desc;
 	GVariant *def;
-    GSList *values;
+	GSList *values;
 };
 
 struct srd_decoder_annotation_row {
@@ -221,7 +220,7 @@ struct srd_decoder_annotation_row {
 struct srd_decoder_inst {
 	struct srd_decoder *decoder;
 	struct srd_session *sess;
-	PyObject *py_inst;
+	void *py_inst;
 	char *inst_id;
 	GSList *pd_output;
 	int dec_num_channels;
@@ -249,7 +248,7 @@ struct srd_proto_data {
 	void *data;
 };
 struct srd_proto_data_annotation {
-	int ann_format;
+	int ann_class;
 	char **ann_text;
 };
 struct srd_proto_data_binary {
@@ -267,19 +266,6 @@ struct srd_pd_callback {
 	void *cb_data;
 };
 
-/* Custom Python types: */
-
-typedef struct {
-	PyObject_HEAD
-	struct srd_decoder_inst *di;
-	uint64_t start_samplenum;
-	unsigned int itercnt;
-	uint8_t *inbuf;
-	uint64_t inbuflen;
-	PyObject *sample;
-} srd_logic;
-
-
 /* srd.c */
 SRD_API int srd_init(const char *path);
 SRD_API int srd_exit(void);
@@ -291,7 +277,7 @@ SRD_API int srd_session_metadata_set(struct srd_session *sess, int key,
 		GVariant *data);
 SRD_API int srd_session_send(struct srd_session *sess,
 		uint64_t start_samplenum, uint64_t end_samplenum,
-		const uint8_t *inbuf, uint64_t inbuflen);
+		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize);
 SRD_API int srd_session_destroy(struct srd_session *sess);
 SRD_API int srd_pd_output_callback_add(struct srd_session *sess,
 		int output_type, srd_pd_output_callback cb, void *cb_data);
@@ -309,7 +295,7 @@ SRD_API int srd_decoder_unload_all(void);
 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
 		GHashTable *options);
 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
-		GHashTable *channels, int unit_size);
+		GHashTable *channels);
 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
 		const char *id, GHashTable *options);
 SRD_API int srd_inst_stack(struct srd_session *sess,
@@ -324,8 +310,6 @@ SRD_API int srd_log_loglevel_set(int loglevel);
 SRD_API int srd_log_loglevel_get(void);
 SRD_API int srd_log_callback_set(srd_log_callback cb, void *cb_data);
 SRD_API int srd_log_callback_set_default(void);
-SRD_API int srd_log_logdomain_set(const char *logdomain);
-SRD_API char *srd_log_logdomain_get(void);
 
 /* error.c */
 SRD_API const char *srd_strerror(int error_code);
diff --git a/libsigrokdecode.pc.in b/libsigrokdecode.pc.in
index b180f27..3051145 100644
--- a/libsigrokdecode.pc.in
+++ b/libsigrokdecode.pc.in
@@ -2,14 +2,17 @@ prefix=@prefix@
 exec_prefix=@exec_prefix@
 libdir=@libdir@
 includedir=@includedir@
+datarootdir=@datarootdir@
+datadir=@datadir@
+pkgdatadir=${datadir}/@PACKAGE_TARNAME@
+decodersdir=${pkgdatadir}/decoders
 
 Name: libsigrokdecode
 Description: Protocol decoder library of the sigrok logic analyzer software
 URL: http://www.sigrok.org
-Requires:
-Requires.private: glib-2.0
-Version: @VERSION@
+Requires: glib-2.0
+Requires.private: @SRD_PKGLIBS@
+Version: @SRD_PACKAGE_VERSION@
 Libs: -L${libdir} -lsigrokdecode
-Libs.private: @LDFLAGS_PYTHON@
-Cflags: -I${includedir} @CPPFLAGS_PYTHON@
-
+Libs.private: @SRD_EXTRA_LIBS@
+Cflags: -I${includedir}
diff --git a/log.c b/log.c
index 1723a0e..0d8bbfa 100644
--- a/log.c
+++ b/log.c
@@ -18,10 +18,12 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <stdarg.h>
 #include <stdio.h>
+#include <glib/gprintf.h>
 
 /**
  * @file
@@ -53,13 +55,6 @@ static srd_log_callback srd_log_cb = srd_logv;
  */
 static void *srd_log_cb_data = NULL;
 
-/* Log domain (a short string that is used as prefix for all messages). */
-/** @cond PRIVATE */
-#define LOGDOMAIN_MAXLEN 30
-#define LOGDOMAIN_DEFAULT "srd: "
-/** @endcond */
-static char srd_log_domain[LOGDOMAIN_MAXLEN + 1] = LOGDOMAIN_DEFAULT;
-
 /**
  * Set the libsigrokdecode loglevel.
  *
@@ -105,50 +100,6 @@ SRD_API int srd_log_loglevel_get(void)
 }
 
 /**
- * Set the libsigrokdecode logdomain string.
- *
- * @param logdomain The string to use as logdomain for libsigrokdecode log
- *                  messages from now on. Must not be NULL. The maximum
- *                  length of the string is 30 characters (this does not
- *                  include the trailing NUL-byte). Longer strings are
- *                  silently truncated.
- *                  In order to not use a logdomain, pass an empty string.
- *                  The function makes its own copy of the input string, i.e.
- *                  the caller does not need to keep it around.
- *
- * @return SRD_OK upon success, SRD_ERR_ARG upon invalid logdomain.
- *
- * @since 0.1.0
- */
-SRD_API int srd_log_logdomain_set(const char *logdomain)
-{
-	if (!logdomain) {
-		srd_err("log: %s: logdomain was NULL", __func__);
-		return SRD_ERR_ARG;
-	}
-
-	snprintf((char *)&srd_log_domain, LOGDOMAIN_MAXLEN, "%s", logdomain);
-
-	srd_dbg("Log domain set to '%s'.", (const char *)&srd_log_domain);
-
-	return SRD_OK;
-}
-
-/**
- * Get the currently configured libsigrokdecode logdomain.
- *
- * @return A copy of the currently configured libsigrokdecode logdomain
- *         string. The caller is responsible for g_free()ing the string when
- *         it is no longer needed.
- *
- * @since 0.1.0
- */
-SRD_API char *srd_log_logdomain_get(void)
-{
-	return g_strdup((const char *)&srd_log_domain);
-}
-
-/**
  * Set the libsigrokdecode log callback to the specified function.
  *
  * @param cb Function pointer to the log callback function to use.
@@ -203,8 +154,6 @@ SRD_API int srd_log_callback_set_default(void)
 static int srd_logv(void *cb_data, int loglevel, const char *format,
 		    va_list args)
 {
-	int ret;
-
 	/* This specific log callback doesn't need the void pointer data. */
 	(void)cb_data;
 
@@ -212,12 +161,12 @@ static int srd_logv(void *cb_data, int loglevel, const char *format,
 	if (loglevel > cur_loglevel)
 		return SRD_OK;
 
-	if (srd_log_domain[0] != '\0')
-		fprintf(stderr, "%s", srd_log_domain);
-	ret = vfprintf(stderr, format, args);
-	fprintf(stderr, "\n");
+	if (fputs("srd: ", stderr) < 0
+			|| g_vfprintf(stderr, format, args) < 0
+			|| putc('\n', stderr) < 0)
+		return SRD_ERR;
 
-	return ret;
+	return SRD_OK;
 }
 
 /** @private */
@@ -233,69 +182,4 @@ SRD_PRIV int srd_log(int loglevel, const char *format, ...)
 	return ret;
 }
 
-/** @private */
-SRD_PRIV int srd_spew(const char *format, ...)
-{
-	int ret;
-	va_list args;
-
-	va_start(args, format);
-	ret = srd_log_cb(srd_log_cb_data, SRD_LOG_SPEW, format, args);
-	va_end(args);
-
-	return ret;
-}
-
-/** @private */
-SRD_PRIV int srd_dbg(const char *format, ...)
-{
-	int ret;
-	va_list args;
-
-	va_start(args, format);
-	ret = srd_log_cb(srd_log_cb_data, SRD_LOG_DBG, format, args);
-	va_end(args);
-
-	return ret;
-}
-
-/** @private */
-SRD_PRIV int srd_info(const char *format, ...)
-{
-	int ret;
-	va_list args;
-
-	va_start(args, format);
-	ret = srd_log_cb(srd_log_cb_data, SRD_LOG_INFO, format, args);
-	va_end(args);
-
-	return ret;
-}
-
-/** @private */
-SRD_PRIV int srd_warn(const char *format, ...)
-{
-	int ret;
-	va_list args;
-
-	va_start(args, format);
-	ret = srd_log_cb(srd_log_cb_data, SRD_LOG_WARN, format, args);
-	va_end(args);
-
-	return ret;
-}
-
-/** @private */
-SRD_PRIV int srd_err(const char *format, ...)
-{
-	int ret;
-	va_list args;
-
-	va_start(args, format);
-	ret = srd_log_cb(srd_log_cb_data, SRD_LOG_ERR, format, args);
-	va_end(args);
-
-	return ret;
-}
-
 /** @} */
diff --git a/autostuff/libtool.m4 b/m4/libtool.m4
similarity index 72%
rename from autostuff/libtool.m4
rename to m4/libtool.m4
index d7c043f..ee80844 100644
--- a/autostuff/libtool.m4
+++ b/m4/libtool.m4
@@ -1,8 +1,6 @@
 # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
 #
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
+#   Copyright (C) 1996-2001, 2003-2015 Free Software Foundation, Inc.
 #   Written by Gordon Matzigkeit, 1996
 #
 # This file is free software; the Free Software Foundation gives
@@ -10,36 +8,30 @@
 # modifications, as long as this notice is preserved.
 
 m4_define([_LT_COPYING], [dnl
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool 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.
+# Copyright (C) 2014 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+# GNU Libtool 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 of the License, or
+# (at your option) any later version.
 #
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program or library that is built
+# using GNU Libtool, you may include this file under the  same
+# distribution terms that you use for the rest of that program.
 #
-# GNU Libtool is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ])
 
-# serial 57 LT_INIT
+# serial 58 LT_INIT
 
 
 # LT_PREREQ(VERSION)
@@ -67,7 +59,7 @@ esac
 # LT_INIT([OPTIONS])
 # ------------------
 AC_DEFUN([LT_INIT],
-[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+[AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK
 AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
 AC_BEFORE([$0], [LT_LANG])dnl
 AC_BEFORE([$0], [LT_OUTPUT])dnl
@@ -91,7 +83,7 @@ dnl Parse OPTIONS
 _LT_SET_OPTIONS([$0], [$1])
 
 # This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
+LIBTOOL_DEPS=$ltmain
 
 # Always use our own libtool.
 LIBTOOL='$(SHELL) $(top_builddir)/libtool'
@@ -111,26 +103,43 @@ dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
 dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
 
 
+# _LT_PREPARE_CC_BASENAME
+# -----------------------
+m4_defun([_LT_PREPARE_CC_BASENAME], [
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+func_cc_basename ()
+{
+    for cc_temp in @S|@*""; do
+      case $cc_temp in
+        compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+        distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+        \-*) ;;
+        *) break;;
+      esac
+    done
+    func_cc_basename_result=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+}
+])# _LT_PREPARE_CC_BASENAME
+
+
 # _LT_CC_BASENAME(CC)
 # -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+# It would be clearer to call AC_REQUIREs from _LT_PREPARE_CC_BASENAME,
+# but that macro is also expanded into generated libtool script, which
+# arranges for $SED and $ECHO to be set by different means.
 m4_defun([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
+[m4_require([_LT_PREPARE_CC_BASENAME])dnl
+AC_REQUIRE([_LT_DECL_SED])dnl
+AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
+func_cc_basename $1
+cc_basename=$func_cc_basename_result
 ])
 
 
 # _LT_FILEUTILS_DEFAULTS
 # ----------------------
 # It is okay to use these file commands and assume they have been set
-# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+# sensibly after 'm4_require([_LT_FILEUTILS_DEFAULTS])'.
 m4_defun([_LT_FILEUTILS_DEFAULTS],
 [: ${CP="cp -f"}
 : ${MV="mv -f"}
@@ -177,15 +186,16 @@ m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
 m4_require([_LT_CMD_OLD_ARCHIVE])dnl
 m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
 m4_require([_LT_WITH_SYSROOT])dnl
+m4_require([_LT_CMD_TRUNCATE])dnl
 
 _LT_CONFIG_LIBTOOL_INIT([
-# See if we are running on zsh, and set the options which allow our
+# See if we are running on zsh, and set the options that allow our
 # commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
+if test -n "\${ZSH_VERSION+set}"; then
    setopt NO_GLOB_SUBST
 fi
 ])
-if test -n "${ZSH_VERSION+set}" ; then
+if test -n "${ZSH_VERSION+set}"; then
    setopt NO_GLOB_SUBST
 fi
 
@@ -198,7 +208,7 @@ aix3*)
   # AIX sometimes has problems with the GCC collect2 program.  For some
   # reason, if we set the COLLECT_NAMES environment variable, the problems
   # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
+  if test set != "${COLLECT_NAMES+set}"; then
     COLLECT_NAMES=
     export COLLECT_NAMES
   fi
@@ -209,14 +219,14 @@ esac
 ofile=libtool
 can_build_shared=yes
 
-# All known linkers require a `.a' archive for static linking (except MSVC,
+# All known linkers require a '.a' archive for static linking (except MSVC,
 # which needs '.lib').
 libext=a
 
-with_gnu_ld="$lt_cv_prog_gnu_ld"
+with_gnu_ld=$lt_cv_prog_gnu_ld
 
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
+old_CC=$CC
+old_CFLAGS=$CFLAGS
 
 # Set sane defaults for various variables
 test -z "$CC" && CC=cc
@@ -269,14 +279,14 @@ no_glob_subst='s/\*/\\\*/g'
 
 # _LT_PROG_LTMAIN
 # ---------------
-# Note that this code is called both from `configure', and `config.status'
+# Note that this code is called both from 'configure', and 'config.status'
 # now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
-# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# 'config.status' has no value for ac_aux_dir unless we are using Automake,
 # so we pass a copy along to make sure it has a sensible value anyway.
 m4_defun([_LT_PROG_LTMAIN],
 [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
 _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
-ltmain="$ac_aux_dir/ltmain.sh"
+ltmain=$ac_aux_dir/ltmain.sh
 ])# _LT_PROG_LTMAIN
 
 
@@ -286,7 +296,7 @@ ltmain="$ac_aux_dir/ltmain.sh"
 
 # So that we can recreate a full libtool script including additional
 # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
-# in macros and then make a single call at the end using the `libtool'
+# in macros and then make a single call at the end using the 'libtool'
 # label.
 
 
@@ -421,8 +431,8 @@ m4_define([_lt_decl_all_varnames],
 
 # _LT_CONFIG_STATUS_DECLARE([VARNAME])
 # ------------------------------------
-# Quote a variable value, and forward it to `config.status' so that its
-# declaration there will have the same value as in `configure'.  VARNAME
+# Quote a variable value, and forward it to 'config.status' so that its
+# declaration there will have the same value as in 'configure'.  VARNAME
 # must have a single quote delimited value for this to work.
 m4_define([_LT_CONFIG_STATUS_DECLARE],
 [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
@@ -446,7 +456,7 @@ m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
 # Output comment and list of tags supported by the script
 m4_defun([_LT_LIBTOOL_TAGS],
 [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
-available_tags="_LT_TAGS"dnl
+available_tags='_LT_TAGS'dnl
 ])
 
 
@@ -474,7 +484,7 @@ m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
 # _LT_LIBTOOL_CONFIG_VARS
 # -----------------------
 # Produce commented declarations of non-tagged libtool config variables
-# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# suitable for insertion in the LIBTOOL CONFIG section of the 'libtool'
 # script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
 # section) are produced by _LT_LIBTOOL_TAG_VARS.
 m4_defun([_LT_LIBTOOL_CONFIG_VARS],
@@ -500,8 +510,8 @@ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
 # Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
 # variables for single and double quote escaping we saved from calls
 # to _LT_DECL, we can put quote escaped variables declarations
-# into `config.status', and then the shell code to quote escape them in
-# for loops in `config.status'.  Finally, any additional code accumulated
+# into 'config.status', and then the shell code to quote escape them in
+# for loops in 'config.status'.  Finally, any additional code accumulated
 # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
 m4_defun([_LT_CONFIG_COMMANDS],
 [AC_PROVIDE_IFELSE([LT_OUTPUT],
@@ -547,7 +557,7 @@ for var in lt_decl_all_varnames([[ \
 ]], lt_decl_quote_varnames); do
     case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes
       ;;
     *)
       eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
@@ -560,7 +570,7 @@ for var in lt_decl_all_varnames([[ \
 ]], lt_decl_dquote_varnames); do
     case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
     *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ## exclude from sc_prohibit_nested_quotes
       ;;
     *)
       eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
@@ -576,7 +586,7 @@ _LT_OUTPUT_LIBTOOL_INIT
 # Generate a child script FILE with all initialization necessary to
 # reuse the environment learned by the parent script, and make the
 # file executable.  If COMMENT is supplied, it is inserted after the
-# `#!' sequence but before initialization text begins.  After this
+# '#!' sequence but before initialization text begins.  After this
 # macro, additional text can be appended to FILE to form the body of
 # the child script.  The macro ends with non-zero status if the
 # file could not be fully written (such as if the disk is full).
@@ -598,7 +608,7 @@ AS_SHELL_SANITIZE
 _AS_PREPARE
 exec AS_MESSAGE_FD>&1
 _ASEOF
-test $lt_write_fail = 0 && chmod +x $1[]dnl
+test 0 = "$lt_write_fail" && chmod +x $1[]dnl
 m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
 
 # LT_OUTPUT
@@ -621,7 +631,7 @@ exec AS_MESSAGE_LOG_FD>>config.log
 } >&AS_MESSAGE_LOG_FD
 
 lt_cl_help="\
-\`$as_me' creates a local libtool stub from the current configuration,
+'$as_me' creates a local libtool stub from the current configuration,
 for use in further configure time tests before the real libtool is
 generated.
 
@@ -643,7 +653,7 @@ Copyright (C) 2011 Free Software Foundation, Inc.
 This config.lt script is free software; the Free Software Foundation
 gives unlimited permision to copy, distribute and modify it."
 
-while test $[#] != 0
+while test 0 != $[#]
 do
   case $[1] in
     --version | --v* | -V )
@@ -656,10 +666,10 @@ do
       lt_cl_silent=: ;;
 
     -*) AC_MSG_ERROR([unrecognized option: $[1]
-Try \`$[0] --help' for more information.]) ;;
+Try '$[0] --help' for more information.]) ;;
 
     *) AC_MSG_ERROR([unrecognized argument: $[1]
-Try \`$[0] --help' for more information.]) ;;
+Try '$[0] --help' for more information.]) ;;
   esac
   shift
 done
@@ -685,7 +695,7 @@ chmod +x "$CONFIG_LT"
 # open by configure.  Here we exec the FD to /dev/null, effectively closing
 # config.log, so it can be properly (re)opened and appended to by config.lt.
 lt_cl_success=:
-test "$silent" = yes &&
+test yes = "$silent" &&
   lt_config_lt_args="$lt_config_lt_args --quiet"
 exec AS_MESSAGE_LOG_FD>/dev/null
 $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
@@ -705,27 +715,30 @@ m4_defun([_LT_CONFIG],
 _LT_CONFIG_SAVE_COMMANDS([
   m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
   m4_if(_LT_TAG, [C], [
-    # See if we are running on zsh, and set the options which allow our
+    # See if we are running on zsh, and set the options that allow our
     # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
+    if test -n "${ZSH_VERSION+set}"; then
       setopt NO_GLOB_SUBST
     fi
 
-    cfgfile="${ofile}T"
+    cfgfile=${ofile}T
     trap "$RM \"$cfgfile\"; exit 1" 1 2 15
     $RM "$cfgfile"
 
     cat <<_LT_EOF >> "$cfgfile"
 #! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# Generated automatically by $as_me ($PACKAGE) $VERSION
 # NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
+
+# Provide generalized library-building support services.
+# Written by Gordon Matzigkeit, 1996
+
 _LT_COPYING
 _LT_LIBTOOL_TAGS
 
+# Configured defaults for sys_lib_dlsearch_path munging.
+: \${LT_SYS_LIBRARY_PATH="$configure_time_lt_sys_library_path"}
+
 # ### BEGIN LIBTOOL CONFIG
 _LT_LIBTOOL_CONFIG_VARS
 _LT_LIBTOOL_TAG_VARS
@@ -733,13 +746,24 @@ _LT_LIBTOOL_TAG_VARS
 
 _LT_EOF
 
+    cat <<'_LT_EOF' >> "$cfgfile"
+
+# ### BEGIN FUNCTIONS SHARED WITH CONFIGURE
+
+_LT_PREPARE_MUNGE_PATH_LIST
+_LT_PREPARE_CC_BASENAME
+
+# ### END FUNCTIONS SHARED WITH CONFIGURE
+
+_LT_EOF
+
   case $host_os in
   aix3*)
     cat <<\_LT_EOF >> "$cfgfile"
 # AIX sometimes has problems with the GCC collect2 program.  For some
 # reason, if we set the COLLECT_NAMES environment variable, the problems
 # vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
+if test set != "${COLLECT_NAMES+set}"; then
   COLLECT_NAMES=
   export COLLECT_NAMES
 fi
@@ -756,8 +780,6 @@ _LT_EOF
   sed '$q' "$ltmain" >> "$cfgfile" \
      || (rm -f "$cfgfile"; exit 1)
 
-  _LT_PROG_REPLACE_SHELLFNS
-
    mv -f "$cfgfile" "$ofile" ||
     (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
   chmod +x "$ofile"
@@ -775,7 +797,6 @@ _LT_EOF
 [m4_if([$1], [], [
     PACKAGE='$PACKAGE'
     VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
     RM='$RM'
     ofile='$ofile'], [])
 ])dnl /_LT_CONFIG_SAVE_COMMANDS
@@ -974,7 +995,7 @@ m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
 
     AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
       [lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
+      if test -z "$LT_MULTI_MODULE"; then
 	# By default we will add the -single_module flag. You can override
 	# by either setting the environment variable LT_MULTI_MODULE
 	# non-empty at configure time, or by adding -multi_module to the
@@ -992,7 +1013,7 @@ m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
 	  cat conftest.err >&AS_MESSAGE_LOG_FD
 	# Otherwise, if the output was created with a 0 exit code from
 	# the compiler, it worked.
-	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
+	elif test -f libconftest.dylib && test 0 = "$_lt_result"; then
 	  lt_cv_apple_cc_single_mod=yes
 	else
 	  cat conftest.err >&AS_MESSAGE_LOG_FD
@@ -1010,7 +1031,7 @@ m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
       AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
 	[lt_cv_ld_exported_symbols_list=yes],
 	[lt_cv_ld_exported_symbols_list=no])
-	LDFLAGS="$save_LDFLAGS"
+	LDFLAGS=$save_LDFLAGS
     ])
 
     AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
@@ -1032,7 +1053,7 @@ _LT_EOF
       _lt_result=$?
       if test -s conftest.err && $GREP force_load conftest.err; then
 	cat conftest.err >&AS_MESSAGE_LOG_FD
-      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
+      elif test -f conftest && test 0 = "$_lt_result" && $GREP forced_load conftest >/dev/null 2>&1; then
 	lt_cv_ld_force_load=yes
       else
 	cat conftest.err >&AS_MESSAGE_LOG_FD
@@ -1042,32 +1063,32 @@ _LT_EOF
     ])
     case $host_os in
     rhapsody* | darwin1.[[012]])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+      _lt_dar_allow_undefined='$wl-undefined ${wl}suppress' ;;
     darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+      _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;;
     darwin*) # darwin 5.x on
       # if running on 10.5 or later, the deployment target defaults
       # to the OS version, if on x86, and 10.4, the deployment
       # target defaults to 10.4. Don't you love it?
       case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
 	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[[012]]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+	  _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;;
+	10.[[012]][[,.]]*)
+	  _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;;
 	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+	  _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;;
       esac
     ;;
   esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+    if test yes = "$lt_cv_apple_cc_single_mod"; then
       _lt_dar_single_mod='$single_module'
     fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    if test yes = "$lt_cv_ld_exported_symbols_list"; then
+      _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym'
     else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/$libname-symbols.expsym $lib'
     fi
-    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
+    if test : != "$DSYMUTIL" && test no = "$lt_cv_ld_force_load"; then
       _lt_dsymutil='~$DSYMUTIL $lib || :'
     else
       _lt_dsymutil=
@@ -1087,29 +1108,29 @@ m4_defun([_LT_DARWIN_LINKER_FEATURES],
   _LT_TAGVAR(hardcode_direct, $1)=no
   _LT_TAGVAR(hardcode_automatic, $1)=yes
   _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  if test "$lt_cv_ld_force_load" = "yes"; then
-    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
+  if test yes = "$lt_cv_ld_force_load"; then
+    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience $wl-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
     m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
                   [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
   else
     _LT_TAGVAR(whole_archive_flag_spec, $1)=''
   fi
   _LT_TAGVAR(link_all_deplibs, $1)=yes
-  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  _LT_TAGVAR(allow_undefined_flag, $1)=$_lt_dar_allow_undefined
   case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
+     ifort*|nagfor*) _lt_dar_can_shared=yes ;;
      *) _lt_dar_can_shared=$GCC ;;
   esac
-  if test "$_lt_dar_can_shared" = "yes"; then
+  if test yes = "$_lt_dar_can_shared"; then
     output_verbose_link_cmd=func_echo_all
-    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
-    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dsymutil"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil"
     m4_if([$1], [CXX],
-[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
-      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
-      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+[   if test yes != "$lt_cv_apple_cc_single_mod"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil"
     fi
 ],[])
   else
@@ -1129,7 +1150,7 @@ m4_defun([_LT_DARWIN_LINKER_FEATURES],
 # Allow to override them for all tags through lt_cv_aix_libpath.
 m4_defun([_LT_SYS_MODULE_PATH_AIX],
 [m4_require([_LT_DECL_SED])dnl
-if test "${lt_cv_aix_libpath+set}" = set; then
+if test set = "${lt_cv_aix_libpath+set}"; then
   aix_libpath=$lt_cv_aix_libpath
 else
   AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
@@ -1147,7 +1168,7 @@ else
     _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
   fi],[])
   if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
-    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
+    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=/usr/lib:/lib
   fi
   ])
   aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
@@ -1167,8 +1188,8 @@ m4_define([_LT_SHELL_INIT],
 # -----------------------
 # Find how we can fake an echo command that does not interpret backslash.
 # In particular, with Autoconf 2.60 or later we add some code to the start
-# of the generated configure script which will find a shell with a builtin
-# printf (which we can use as an echo command).
+# of the generated configure script that will find a shell with a builtin
+# printf (that we can use as an echo command).
 m4_defun([_LT_PROG_ECHO_BACKSLASH],
 [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
 ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
@@ -1196,10 +1217,10 @@ fi
 # Invoke $ECHO with all args, space-separated.
 func_echo_all ()
 {
-    $ECHO "$*" 
+    $ECHO "$*"
 }
 
-case "$ECHO" in
+case $ECHO in
   printf*) AC_MSG_RESULT([printf]) ;;
   print*) AC_MSG_RESULT([print -r]) ;;
   *) AC_MSG_RESULT([cat]) ;;
@@ -1225,16 +1246,17 @@ _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
 AC_DEFUN([_LT_WITH_SYSROOT],
 [AC_MSG_CHECKING([for sysroot])
 AC_ARG_WITH([sysroot],
-[  --with-sysroot[=DIR] Search for dependent libraries within DIR
-                        (or the compiler's sysroot if not specified).],
+[AS_HELP_STRING([--with-sysroot@<:@=DIR@:>@],
+  [Search for dependent libraries within DIR (or the compiler's sysroot
+   if not specified).])],
 [], [with_sysroot=no])
 
 dnl lt_sysroot will always be passed unquoted.  We quote it here
 dnl in case the user passed a directory name.
 lt_sysroot=
-case ${with_sysroot} in #(
+case $with_sysroot in #(
  yes)
-   if test "$GCC" = yes; then
+   if test yes = "$GCC"; then
      lt_sysroot=`$CC --print-sysroot 2>/dev/null`
    fi
    ;; #(
@@ -1244,14 +1266,14 @@ case ${with_sysroot} in #(
  no|'')
    ;; #(
  *)
-   AC_MSG_RESULT([${with_sysroot}])
+   AC_MSG_RESULT([$with_sysroot])
    AC_MSG_ERROR([The sysroot must be an absolute path.])
    ;;
 esac
 
  AC_MSG_RESULT([${lt_sysroot:-no}])
 _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
-[dependent libraries, and in which our libraries should be installed.])])
+[dependent libraries, and where our libraries should be installed.])])
 
 # _LT_ENABLE_LOCK
 # ---------------
@@ -1259,31 +1281,33 @@ m4_defun([_LT_ENABLE_LOCK],
 [AC_ARG_ENABLE([libtool-lock],
   [AS_HELP_STRING([--disable-libtool-lock],
     [avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+test no = "$enable_libtool_lock" || enable_libtool_lock=yes
 
 # Some flags need to be propagated to the compiler or linker for good
 # libtool support.
 case $host in
 ia64-*-hpux*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set mode
+  # options accordingly.
   echo 'int i;' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
     case `/usr/bin/file conftest.$ac_objext` in
       *ELF-32*)
-	HPUX_IA64_MODE="32"
+	HPUX_IA64_MODE=32
 	;;
       *ELF-64*)
-	HPUX_IA64_MODE="64"
+	HPUX_IA64_MODE=64
 	;;
     esac
   fi
   rm -rf conftest*
   ;;
 *-*-irix6*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
   echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
+    if test yes = "$lt_cv_prog_gnu_ld"; then
       case `/usr/bin/file conftest.$ac_objext` in
 	*32-bit*)
 	  LD="${LD-ld} -melf32bsmip"
@@ -1312,9 +1336,46 @@ ia64-*-hpux*)
   rm -rf conftest*
   ;;
 
+mips64*-*linux*)
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
+  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    emul=elf
+    case `/usr/bin/file conftest.$ac_objext` in
+      *32-bit*)
+	emul="${emul}32"
+	;;
+      *64-bit*)
+	emul="${emul}64"
+	;;
+    esac
+    case `/usr/bin/file conftest.$ac_objext` in
+      *MSB*)
+	emul="${emul}btsmip"
+	;;
+      *LSB*)
+	emul="${emul}ltsmip"
+	;;
+    esac
+    case `/usr/bin/file conftest.$ac_objext` in
+      *N32*)
+	emul="${emul}n32"
+	;;
+    esac
+    LD="${LD-ld} -m $emul"
+  fi
+  rm -rf conftest*
+  ;;
+
 x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
 s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.  Note that the listed cases only cover the
+  # situations where additional linker options are needed (such as when
+  # doing 32-bit compilation for a host where ld defaults to 64-bit, or
+  # vice versa); the common cases where no linker options are needed do
+  # not appear in the list.
   echo 'int i;' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
     case `/usr/bin/file conftest.o` in
@@ -1333,10 +1394,10 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 		;;
 	    esac
 	    ;;
-	  powerpc64le-*)
+	  powerpc64le-*linux*)
 	    LD="${LD-ld} -m elf32lppclinux"
 	    ;;
-	  powerpc64-*)
+	  powerpc64-*linux*)
 	    LD="${LD-ld} -m elf32ppclinux"
 	    ;;
 	  s390x-*linux*)
@@ -1355,10 +1416,10 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 	  x86_64-*linux*)
 	    LD="${LD-ld} -m elf_x86_64"
 	    ;;
-	  powerpcle-*)
+	  powerpcle-*linux*)
 	    LD="${LD-ld} -m elf64lppc"
 	    ;;
-	  powerpc-*)
+	  powerpc-*linux*)
 	    LD="${LD-ld} -m elf64ppc"
 	    ;;
 	  s390*-*linux*|s390*-*tpf*)
@@ -1376,19 +1437,20 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 
 *-*-sco3.2v5*)
   # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
+  SAVE_CFLAGS=$CFLAGS
   CFLAGS="$CFLAGS -belf"
   AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
     [AC_LANG_PUSH(C)
      AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
      AC_LANG_POP])
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+  if test yes != "$lt_cv_cc_needs_belf"; then
     # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
+    CFLAGS=$SAVE_CFLAGS
   fi
   ;;
 *-*solaris*)
-  # Find out which ABI we are using.
+  # Find out what ABI is being produced by ac_compile, and set linker
+  # options accordingly.
   echo 'int i;' > conftest.$ac_ext
   if AC_TRY_EVAL(ac_compile); then
     case `/usr/bin/file conftest.o` in
@@ -1396,7 +1458,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
       case $lt_cv_prog_gnu_ld in
       yes*)
         case $host in
-        i?86-*-solaris*)
+        i?86-*-solaris*|x86_64-*-solaris*)
           LD="${LD-ld} -m elf_x86_64"
           ;;
         sparc*-*-solaris*)
@@ -1405,7 +1467,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
         esac
         # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
         if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
-          LD="${LD-ld}_sol2"
+          LD=${LD-ld}_sol2
         fi
         ;;
       *)
@@ -1421,7 +1483,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
   ;;
 esac
 
-need_locks="$enable_libtool_lock"
+need_locks=$enable_libtool_lock
 ])# _LT_ENABLE_LOCK
 
 
@@ -1440,11 +1502,11 @@ AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
      [echo conftest.$ac_objext > conftest.lst
       lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
       AC_TRY_EVAL([lt_ar_try])
-      if test "$ac_status" -eq 0; then
+      if test 0 -eq "$ac_status"; then
 	# Ensure the archiver fails upon bogus file names.
 	rm -f conftest.$ac_objext libconftest.a
 	AC_TRY_EVAL([lt_ar_try])
-	if test "$ac_status" -ne 0; then
+	if test 0 -ne "$ac_status"; then
           lt_cv_ar_at_file=@
         fi
       fi
@@ -1452,7 +1514,7 @@ AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
      ])
   ])
 
-if test "x$lt_cv_ar_at_file" = xno; then
+if test no = "$lt_cv_ar_at_file"; then
   archiver_list_spec=
 else
   archiver_list_spec=$lt_cv_ar_at_file
@@ -1483,7 +1545,7 @@ old_postuninstall_cmds=
 
 if test -n "$RANLIB"; then
   case $host_os in
-  openbsd*)
+  bitrig* | openbsd*)
     old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
     ;;
   *)
@@ -1519,7 +1581,7 @@ AC_CACHE_CHECK([$1], [$2],
   [$2=no
    m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
    echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$3"
+   lt_compiler_flag="$3"  ## exclude from sc_useless_quotes_in_assignment
    # Insert the option either (1) after the last *FLAGS variable, or
    # (2) before a word containing "conftest.", or (3) at the end.
    # Note that $ac_compile itself does not contain backslashes and begins
@@ -1546,7 +1608,7 @@ AC_CACHE_CHECK([$1], [$2],
    $RM conftest*
 ])
 
-if test x"[$]$2" = xyes; then
+if test yes = "[$]$2"; then
     m4_if([$5], , :, [$5])
 else
     m4_if([$6], , :, [$6])
@@ -1568,7 +1630,7 @@ AC_DEFUN([_LT_LINKER_OPTION],
 m4_require([_LT_DECL_SED])dnl
 AC_CACHE_CHECK([$1], [$2],
   [$2=no
-   save_LDFLAGS="$LDFLAGS"
+   save_LDFLAGS=$LDFLAGS
    LDFLAGS="$LDFLAGS $3"
    echo "$lt_simple_link_test_code" > conftest.$ac_ext
    if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
@@ -1587,10 +1649,10 @@ AC_CACHE_CHECK([$1], [$2],
      fi
    fi
    $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
+   LDFLAGS=$save_LDFLAGS
 ])
 
-if test x"[$]$2" = xyes; then
+if test yes = "[$]$2"; then
     m4_if([$4], , :, [$4])
 else
     m4_if([$5], , :, [$5])
@@ -1611,7 +1673,7 @@ AC_DEFUN([LT_CMD_MAX_LEN],
 AC_MSG_CHECKING([the maximum length of command line arguments])
 AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
   i=0
-  teststring="ABCD"
+  teststring=ABCD
 
   case $build_os in
   msdosdjgpp*)
@@ -1651,7 +1713,7 @@ AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
     lt_cv_sys_max_cmd_len=8192;
     ;;
 
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+  bitrig* | darwin* | dragonfly* | freebsd* | netbsd* | openbsd*)
     # This has been around since 386BSD, at least.  Likely further.
     if test -x /sbin/sysctl; then
       lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
@@ -1702,22 +1764,22 @@ AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
   *)
     lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
     if test -n "$lt_cv_sys_max_cmd_len" && \
-	test undefined != "$lt_cv_sys_max_cmd_len"; then
+       test undefined != "$lt_cv_sys_max_cmd_len"; then
       lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
       lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
     else
       # Make teststring a little bigger before we do anything with it.
       # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
+      for i in 1 2 3 4 5 6 7 8; do
         teststring=$teststring$teststring
       done
       SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
       # If test is not a shell built-in, we'll probably end up computing a
       # maximum length that is only half of the actual maximum length, but
       # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
+      while { test X`env echo "$teststring$teststring" 2>/dev/null` \
 	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
+	      test 17 != "$i" # 1/2 MB should be enough
       do
         i=`expr $i + 1`
         teststring=$teststring$teststring
@@ -1733,7 +1795,7 @@ AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
     ;;
   esac
 ])
-if test -n $lt_cv_sys_max_cmd_len ; then
+if test -n "$lt_cv_sys_max_cmd_len"; then
   AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
 else
   AC_MSG_RESULT(none)
@@ -1761,7 +1823,7 @@ m4_defun([_LT_HEADER_DLFCN],
 # ----------------------------------------------------------------
 m4_defun([_LT_TRY_DLOPEN_SELF],
 [m4_require([_LT_HEADER_DLFCN])dnl
-if test "$cross_compiling" = yes; then :
+if test yes = "$cross_compiling"; then :
   [$4]
 else
   lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
@@ -1808,9 +1870,9 @@ else
 #  endif
 #endif
 
-/* When -fvisbility=hidden is used, assume the code has been annotated
+/* When -fvisibility=hidden is used, assume the code has been annotated
    correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
+#if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
 int fnord () __attribute__((visibility("default")));
 #endif
 
@@ -1836,7 +1898,7 @@ int main ()
   return status;
 }]
 _LT_EOF
-  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+  if AC_TRY_EVAL(ac_link) && test -s "conftest$ac_exeext" 2>/dev/null; then
     (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
     lt_status=$?
     case x$lt_status in
@@ -1857,7 +1919,7 @@ rm -fr conftest*
 # ------------------
 AC_DEFUN([LT_SYS_DLOPEN_SELF],
 [m4_require([_LT_HEADER_DLFCN])dnl
-if test "x$enable_dlopen" != xyes; then
+if test yes != "$enable_dlopen"; then
   enable_dlopen=unknown
   enable_dlopen_self=unknown
   enable_dlopen_self_static=unknown
@@ -1867,44 +1929,52 @@ else
 
   case $host_os in
   beos*)
-    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen=load_add_on
     lt_cv_dlopen_libs=
     lt_cv_dlopen_self=yes
     ;;
 
   mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen=LoadLibrary
     lt_cv_dlopen_libs=
     ;;
 
   cygwin*)
-    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen=dlopen
     lt_cv_dlopen_libs=
     ;;
 
   darwin*)
-  # if libdl is installed we need to link against it
+    # if libdl is installed we need to link against it
     AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
-    lt_cv_dlopen="dyld"
+		[lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],[
+    lt_cv_dlopen=dyld
     lt_cv_dlopen_libs=
     lt_cv_dlopen_self=yes
     ])
     ;;
 
+  tpf*)
+    # Don't try to run any link tests for TPF.  We know it's impossible
+    # because TPF is a cross-compiler, and we know how we open DSOs.
+    lt_cv_dlopen=dlopen
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=no
+    ;;
+
   *)
     AC_CHECK_FUNC([shl_load],
-	  [lt_cv_dlopen="shl_load"],
+	  [lt_cv_dlopen=shl_load],
       [AC_CHECK_LIB([dld], [shl_load],
-	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+	    [lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld],
 	[AC_CHECK_FUNC([dlopen],
-	      [lt_cv_dlopen="dlopen"],
+	      [lt_cv_dlopen=dlopen],
 	  [AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+		[lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl],
 	    [AC_CHECK_LIB([svld], [dlopen],
-		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+		  [lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld],
 	      [AC_CHECK_LIB([dld], [dld_link],
-		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+		    [lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld])
 	      ])
 	    ])
 	  ])
@@ -1913,21 +1983,21 @@ else
     ;;
   esac
 
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
+  if test no = "$lt_cv_dlopen"; then
     enable_dlopen=no
+  else
+    enable_dlopen=yes
   fi
 
   case $lt_cv_dlopen in
   dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+    save_CPPFLAGS=$CPPFLAGS
+    test yes = "$ac_cv_header_dlfcn_h" && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
 
-    save_LDFLAGS="$LDFLAGS"
+    save_LDFLAGS=$LDFLAGS
     wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
 
-    save_LIBS="$LIBS"
+    save_LIBS=$LIBS
     LIBS="$lt_cv_dlopen_libs $LIBS"
 
     AC_CACHE_CHECK([whether a program can dlopen itself],
@@ -1937,7 +2007,7 @@ else
 	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
     ])
 
-    if test "x$lt_cv_dlopen_self" = xyes; then
+    if test yes = "$lt_cv_dlopen_self"; then
       wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
       AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
 	  lt_cv_dlopen_self_static, [dnl
@@ -1947,9 +2017,9 @@ else
       ])
     fi
 
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
+    CPPFLAGS=$save_CPPFLAGS
+    LDFLAGS=$save_LDFLAGS
+    LIBS=$save_LIBS
     ;;
   esac
 
@@ -2041,8 +2111,8 @@ m4_defun([_LT_COMPILER_FILE_LOCKS],
 m4_require([_LT_FILEUTILS_DEFAULTS])dnl
 _LT_COMPILER_C_O([$1])
 
-hard_links="nottested"
-if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+hard_links=nottested
+if test no = "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" && test no != "$need_locks"; then
   # do not overwrite the value of need_locks provided by the user
   AC_MSG_CHECKING([if we can lock with hard links])
   hard_links=yes
@@ -2052,8 +2122,8 @@ if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" !=
   ln conftest.a conftest.b 2>&5 || hard_links=no
   ln conftest.a conftest.b 2>/dev/null && hard_links=no
   AC_MSG_RESULT([$hard_links])
-  if test "$hard_links" = no; then
-    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+  if test no = "$hard_links"; then
+    AC_MSG_WARN(['$CC' does not support '-c -o', so 'make -j' may be unsafe])
     need_locks=warn
   fi
 else
@@ -2080,8 +2150,8 @@ objdir=$lt_cv_objdir
 _LT_DECL([], [objdir], [0],
          [The name of the directory that contains temporary libtool files])dnl
 m4_pattern_allow([LT_OBJDIR])dnl
-AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
-  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+AC_DEFINE_UNQUOTED([LT_OBJDIR], "$lt_cv_objdir/",
+  [Define to the sub-directory where libtool stores uninstalled libraries.])
 ])# _LT_CHECK_OBJDIR
 
 
@@ -2093,15 +2163,15 @@ m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
 _LT_TAGVAR(hardcode_action, $1)=
 if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
    test -n "$_LT_TAGVAR(runpath_var, $1)" ||
-   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+   test yes = "$_LT_TAGVAR(hardcode_automatic, $1)"; then
 
   # We can hardcode non-existent directories.
-  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+  if test no != "$_LT_TAGVAR(hardcode_direct, $1)" &&
      # If the only mechanism to avoid hardcoding is shlibpath_var, we
      # have to relink, otherwise we might link with an installed library
      # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
-     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+     ## test no != "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" &&
+     test no != "$_LT_TAGVAR(hardcode_minus_L, $1)"; then
     # Linking always hardcodes the temporary library directory.
     _LT_TAGVAR(hardcode_action, $1)=relink
   else
@@ -2115,12 +2185,12 @@ else
 fi
 AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
 
-if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
-   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+if test relink = "$_LT_TAGVAR(hardcode_action, $1)" ||
+   test yes = "$_LT_TAGVAR(inherit_rpath, $1)"; then
   # Fast installation is not supported
   enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
+elif test yes = "$shlibpath_overrides_runpath" ||
+     test no = "$enable_shared"; then
   # Fast installation is not necessary
   enable_fast_install=needless
 fi
@@ -2144,7 +2214,7 @@ else
 # FIXME - insert some real tests, host_os isn't really good enough
   case $host_os in
   darwin*)
-    if test -n "$STRIP" ; then
+    if test -n "$STRIP"; then
       striplib="$STRIP -x"
       old_striplib="$STRIP -S"
       AC_MSG_RESULT([yes])
@@ -2162,6 +2232,47 @@ _LT_DECL([], [striplib], [1])
 ])# _LT_CMD_STRIPLIB
 
 
+# _LT_PREPARE_MUNGE_PATH_LIST
+# ---------------------------
+# Make sure func_munge_path_list() is defined correctly.
+m4_defun([_LT_PREPARE_MUNGE_PATH_LIST],
+[[# func_munge_path_list VARIABLE PATH
+# -----------------------------------
+# VARIABLE is name of variable containing _space_ separated list of
+# directories to be munged by the contents of PATH, which is string
+# having a format:
+# "DIR[:DIR]:"
+#       string "DIR[ DIR]" will be prepended to VARIABLE
+# ":DIR[:DIR]"
+#       string "DIR[ DIR]" will be appended to VARIABLE
+# "DIRP[:DIRP]::[DIRA:]DIRA"
+#       string "DIRP[ DIRP]" will be prepended to VARIABLE and string
+#       "DIRA[ DIRA]" will be appended to VARIABLE
+# "DIR[:DIR]"
+#       VARIABLE will be replaced by "DIR[ DIR]"
+func_munge_path_list ()
+{
+    case x at S|@2 in
+    x)
+        ;;
+    *:)
+        eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'` \@S|@@S|@1\"
+        ;;
+    x:*)
+        eval @S|@1=\"\@S|@@S|@1 `$ECHO @S|@2 | $SED 's/:/ /g'`\"
+        ;;
+    *::*)
+        eval @S|@1=\"\@S|@@S|@1\ `$ECHO @S|@2 | $SED -e 's/.*:://' -e 's/:/ /g'`\"
+        eval @S|@1=\"`$ECHO @S|@2 | $SED -e 's/::.*//' -e 's/:/ /g'`\ \@S|@@S|@1\"
+        ;;
+    *)
+        eval @S|@1=\"`$ECHO @S|@2 | $SED 's/:/ /g'`\"
+        ;;
+    esac
+}
+]])# _LT_PREPARE_PATH_LIST
+
+
 # _LT_SYS_DYNAMIC_LINKER([TAG])
 # -----------------------------
 # PORTME Fill in your ld.so characteristics
@@ -2172,17 +2283,18 @@ m4_require([_LT_FILEUTILS_DEFAULTS])dnl
 m4_require([_LT_DECL_OBJDUMP])dnl
 m4_require([_LT_DECL_SED])dnl
 m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_PREPARE_MUNGE_PATH_LIST])dnl
 AC_MSG_CHECKING([dynamic linker characteristics])
 m4_if([$1],
 	[], [
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) lt_awk_arg="/^libraries:/" ;;
+    darwin*) lt_awk_arg='/^libraries:/,/LR/' ;;
+    *) lt_awk_arg='/^libraries:/' ;;
   esac
   case $host_os in
-    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
-    *) lt_sed_strip_eq="s,=/,/,g" ;;
+    mingw* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;;
+    *) lt_sed_strip_eq='s|=/|/|g' ;;
   esac
   lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
   case $lt_search_path_spec in
@@ -2198,28 +2310,35 @@ if test "$GCC" = yes; then
     ;;
   esac
   # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
+  # and add multilib dir if necessary...
   lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  lt_multi_os_dir=/`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  # ...but if some path component already ends with the multilib dir we assume
+  # that all is fine and trust -print-search-dirs as is (GCC 4.2? or newer).
+  case "$lt_multi_os_dir; $lt_search_path_spec " in
+  "/; "* | "/.; "* | "/./; "* | *"$lt_multi_os_dir "* | *"$lt_multi_os_dir/ "*)
+    lt_multi_os_dir=
+    ;;
+  esac
   for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
+    if test -d "$lt_sys_path$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path$lt_multi_os_dir"
+    elif test -n "$lt_multi_os_dir"; then
       test -d "$lt_sys_path" && \
 	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
     fi
   done
   lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
+BEGIN {RS = " "; FS = "/|\n";} {
+  lt_foo = "";
+  lt_count = 0;
   for (lt_i = NF; lt_i > 0; lt_i--) {
     if ($lt_i != "" && $lt_i != ".") {
       if ($lt_i == "..") {
         lt_count++;
       } else {
         if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
+          lt_foo = "/" $lt_i lt_foo;
         } else {
           lt_count--;
         }
@@ -2233,7 +2352,7 @@ BEGIN {RS=" "; FS="/|\n";} {
   # for these hosts.
   case $host_os in
     mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
-      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
+      $SED 's|/\([[A-Za-z]]:\)|\1|g'` ;;
   esac
   sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
 else
@@ -2242,7 +2361,7 @@ fi])
 library_names_spec=
 libname_spec='lib$name'
 soname_spec=
-shrext_cmds=".so"
+shrext_cmds=.so
 postinstall_cmds=
 postuninstall_cmds=
 finish_cmds=
@@ -2259,14 +2378,17 @@ hardcode_into_libs=no
 # flags to be left without arguments
 need_version=unknown
 
+AC_ARG_VAR([LT_SYS_LIBRARY_PATH],
+[User-defined run-time library search path.])
+
 case $host_os in
 aix3*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname.a'
   shlibpath_var=LIBPATH
 
   # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
+  soname_spec='$libname$release$shared_ext$major'
   ;;
 
 aix[[4-9]]*)
@@ -2274,41 +2396,91 @@ aix[[4-9]]*)
   need_lib_prefix=no
   need_version=no
   hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
+  if test ia64 = "$host_cpu"; then
     # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    library_names_spec='$libname$release$shared_ext$major $libname$release$shared_ext$versuffix $libname$shared_ext'
     shlibpath_var=LD_LIBRARY_PATH
   else
     # With GCC up to 2.95.x, collect2 would create an import file
     # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
+    # the line '#! .'.  This would cause the generated library to
+    # depend on '.', always an invalid library.  This was fixed in
     # development snapshots of GCC prior to 3.0.
     case $host_os in
       aix4 | aix4.[[01]] | aix4.[[01]].*)
       if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
 	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+	   echo '#endif'; } | $CC -E - | $GREP yes > /dev/null; then
 	:
       else
 	can_build_shared=no
       fi
       ;;
     esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # Using Import Files as archive members, it is possible to support
+    # filename-based versioning of shared library archives on AIX. While
+    # this would work for both with and without runtime linking, it will
+    # prevent static linking of such archives. So we do filename-based
+    # shared library versioning with .so extension only, which is used
+    # when both runtime linking and shared linking is enabled.
+    # Unfortunately, runtime linking may impact performance, so we do
+    # not want this to be the default eventually. Also, we use the
+    # versioned .so libs for executables only if there is the -brtl
+    # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only.
+    # To allow for filename-based versioning support, we need to create
+    # libNAME.so.V as an archive file, containing:
+    # *) an Import File, referring to the versioned filename of the
+    #    archive as well as the shared archive member, telling the
+    #    bitwidth (32 or 64) of that shared object, and providing the
+    #    list of exported symbols of that shared object, eventually
+    #    decorated with the 'weak' keyword
+    # *) the shared object with the F_LOADONLY flag set, to really avoid
+    #    it being seen by the linker.
+    # At run time we better use the real file rather than another symlink,
+    # but for link time we create the symlink libNAME.so -> libNAME.so.V
+
+    case $with_aix_soname,$aix_use_runtimelinking in
+    # AIX (on Power*) has no versioning support, so currently we cannot hardcode correct
     # soname into executable. Probably we can add versioning support to
     # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
+    aix,yes) # traditional libtool
+      dynamic_linker='AIX unversionable lib.so'
       # If using run time linking (on AIX 4.2 or later) use lib<name>.so
       # instead of lib<name>.a to let people know that these are not
       # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+      ;;
+    aix,no) # traditional AIX only
+      dynamic_linker='AIX lib.a[(]lib.so.V[)]'
       # We preserve .a as extension for shared libraries through AIX4.2
       # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
+      library_names_spec='$libname$release.a $libname.a'
+      soname_spec='$libname$release$shared_ext$major'
+      ;;
+    svr4,*) # full svr4 only
+      dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)]"
+      library_names_spec='$libname$release$shared_ext$major $libname$shared_ext'
+      # We do not specify a path in Import Files, so LIBPATH fires.
+      shlibpath_overrides_runpath=yes
+      ;;
+    *,yes) # both, prefer svr4
+      dynamic_linker="AIX lib.so.V[(]$shared_archive_member_spec.o[)], lib.a[(]lib.so.V[)]"
+      library_names_spec='$libname$release$shared_ext$major $libname$shared_ext'
+      # unpreferred sharedlib libNAME.a needs extra handling
+      postinstall_cmds='test -n "$linkname" || linkname="$realname"~func_stripname "" ".so" "$linkname"~$install_shared_prog "$dir/$func_stripname_result.$libext" "$destdir/$func_stripname_result.$libext"~test -z "$tstripme" || test -z "$striplib" || $striplib "$destdir/$func_stripname_result.$libext"'
+      postuninstall_cmds='for n in $library_names $old_library; do :; done~func_stripname "" ".so" "$n"~test "$func_stripname_result" = "$n" || func_append rmfiles " $odir/$func_stripname_result.$libext"'
+      # We do not specify a path in Import Files, so LIBPATH fires.
+      shlibpath_overrides_runpath=yes
+      ;;
+    *,no) # both, prefer aix
+      dynamic_linker="AIX lib.a[(]lib.so.V[)], lib.so.V[(]$shared_archive_member_spec.o[)]"
+      library_names_spec='$libname$release.a $libname.a'
+      soname_spec='$libname$release$shared_ext$major'
+      # unpreferred sharedlib libNAME.so.V and symlink libNAME.so need extra handling
+      postinstall_cmds='test -z "$dlname" || $install_shared_prog $dir/$dlname $destdir/$dlname~test -z "$tstripme" || test -z "$striplib" || $striplib $destdir/$dlname~test -n "$linkname" || linkname=$realname~func_stripname "" ".a" "$linkname"~(cd "$destdir" && $LN_S -f $dlname $func_stripname_result.so)'
+      postuninstall_cmds='test -z "$dlname" || func_append rmfiles " $odir/$dlname"~for n in $old_library $library_names; do :; done~func_stripname "" ".a" "$n"~func_append rmfiles " $odir/$func_stripname_result.so"'
+      ;;
+    esac
     shlibpath_var=LIBPATH
   fi
   ;;
@@ -2318,18 +2490,18 @@ amigaos*)
   powerpc)
     # Since July 2007 AmigaOS4 officially supports .so libraries.
     # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
     ;;
   m68k)
     library_names_spec='$libname.ixlibrary $libname.a'
     # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
     ;;
   esac
   ;;
 
 beos*)
-  library_names_spec='${libname}${shared_ext}'
+  library_names_spec='$libname$shared_ext'
   dynamic_linker="$host_os ld.so"
   shlibpath_var=LIBRARY_PATH
   ;;
@@ -2337,8 +2509,8 @@ beos*)
 bsdi[[45]]*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
@@ -2350,7 +2522,7 @@ bsdi[[45]]*)
 
 cygwin* | mingw* | pw32* | cegcc*)
   version_type=windows
-  shrext_cmds=".dll"
+  shrext_cmds=.dll
   need_version=no
   need_lib_prefix=no
 
@@ -2359,8 +2531,8 @@ cygwin* | mingw* | pw32* | cegcc*)
     # gcc
     library_names_spec='$libname.dll.a'
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+    postinstall_cmds='base_file=`basename \$file`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
       $install_prog $dir/$dlname \$dldir/$dlname~
@@ -2376,17 +2548,17 @@ cygwin* | mingw* | pw32* | cegcc*)
     case $host_os in
     cygwin*)
       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      soname_spec='`echo $libname | sed -e 's/^lib/cyg/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
 m4_if([$1], [],[
       sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
       ;;
     mingw* | cegcc*)
       # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
       ;;
     pw32*)
       # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      library_names_spec='`echo $libname | sed -e 's/^lib/pw/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
       ;;
     esac
     dynamic_linker='Win32 ld.exe'
@@ -2395,8 +2567,8 @@ m4_if([$1], [],[
   *,cl*)
     # Native MSVC
     libname_spec='$name'
-    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-    library_names_spec='${libname}.dll.lib'
+    soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
+    library_names_spec='$libname.dll.lib'
 
     case $build_os in
     mingw*)
@@ -2423,7 +2595,7 @@ m4_if([$1], [],[
       sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
       ;;
     *)
-      sys_lib_search_path_spec="$LIB"
+      sys_lib_search_path_spec=$LIB
       if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
         # It is most probably a Windows format PATH.
         sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
@@ -2436,8 +2608,8 @@ m4_if([$1], [],[
     esac
 
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+    postinstall_cmds='base_file=`basename \$file`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~
       dldir=$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
       $install_prog $dir/$dlname \$dldir/$dlname'
@@ -2450,7 +2622,7 @@ m4_if([$1], [],[
 
   *)
     # Assume MSVC wrapper
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    library_names_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext $libname.lib'
     dynamic_linker='Win32 ld.exe'
     ;;
   esac
@@ -2463,8 +2635,8 @@ darwin* | rhapsody*)
   version_type=darwin
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
+  library_names_spec='$libname$release$major$shared_ext $libname$shared_ext'
+  soname_spec='$libname$release$major$shared_ext'
   shlibpath_overrides_runpath=yes
   shlibpath_var=DYLD_LIBRARY_PATH
   shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
@@ -2477,8 +2649,8 @@ dgux*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
@@ -2496,12 +2668,13 @@ freebsd* | dragonfly*)
   version_type=freebsd-$objformat
   case $version_type in
     freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+      soname_spec='$libname$release$shared_ext$major'
       need_version=no
       need_lib_prefix=no
       ;;
     freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
       need_version=yes
       ;;
   esac
@@ -2531,10 +2704,10 @@ haiku*)
   need_lib_prefix=no
   need_version=no
   dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
+  shlibpath_overrides_runpath=no
   sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
   hardcode_into_libs=yes
   ;;
@@ -2552,14 +2725,15 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.so"
     shlibpath_var=LD_LIBRARY_PATH
     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
+    if test 32 = "$HPUX_IA64_MODE"; then
       sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+      sys_lib_dlsearch_path_spec=/usr/lib/hpux32
     else
       sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+      sys_lib_dlsearch_path_spec=/usr/lib/hpux64
     fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
     ;;
   hppa*64*)
     shrext_cmds='.sl'
@@ -2567,8 +2741,8 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.sl"
     shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
     shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
     sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
     ;;
@@ -2577,8 +2751,8 @@ hpux9* | hpux10* | hpux11*)
     dynamic_linker="$host_os dld.sl"
     shlibpath_var=SHLIB_PATH
     shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     ;;
   esac
   # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
@@ -2591,8 +2765,8 @@ interix[[3-9]]*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
@@ -2603,7 +2777,7 @@ irix5* | irix6* | nonstopux*)
   case $host_os in
     nonstopux*) version_type=nonstopux ;;
     *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
+	if test yes = "$lt_cv_prog_gnu_ld"; then
 		version_type=linux # correct to gnu/linux during the next big refactor
 	else
 		version_type=irix
@@ -2611,8 +2785,8 @@ irix5* | irix6* | nonstopux*)
   esac
   need_lib_prefix=no
   need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='$libname$release$shared_ext$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$release$shared_ext $libname$shared_ext'
   case $host_os in
   irix5* | nonstopux*)
     libsuff= shlibsuff=
@@ -2631,8 +2805,8 @@ irix5* | irix6* | nonstopux*)
   esac
   shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
   shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  sys_lib_search_path_spec="/usr/lib$libsuff /lib$libsuff /usr/local/lib$libsuff"
+  sys_lib_dlsearch_path_spec="/usr/lib$libsuff /lib$libsuff"
   hardcode_into_libs=yes
   ;;
 
@@ -2641,13 +2815,33 @@ linux*oldld* | linux*aout* | linux*coff*)
   dynamic_linker=no
   ;;
 
+linux*android*)
+  version_type=none # Android doesn't support versioned libraries.
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='$libname$release$shared_ext'
+  soname_spec='$libname$release$shared_ext'
+  finish_cmds=
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  dynamic_linker='Android linker'
+  # Don't embed -rpath directories since the linker doesn't support them.
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+  ;;
+
 # This must be glibc/ELF.
 linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
@@ -2672,7 +2866,12 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
   # before this can be enabled.
   hardcode_into_libs=yes
 
-  # Append ld.so.conf contents to the search path
+  # Ideally, we could use ldconfig to report *all* directores which are
+  # searched for libraries, however this is still not possible.  Aside from not
+  # being certain /sbin/ldconfig is available, command
+  # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64,
+  # even though it is searched at run-time.  Try to do the best guess by
+  # appending ld.so.conf contents (and includes) to the search path.
   if test -f /etc/ld.so.conf; then
     lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
@@ -2704,12 +2903,12 @@ netbsd*)
   need_lib_prefix=no
   need_version=no
   if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
     finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
     dynamic_linker='NetBSD (a.out) ld.so'
   else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
+    library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+    soname_spec='$libname$release$shared_ext$major'
     dynamic_linker='NetBSD ld.elf_so'
   fi
   shlibpath_var=LD_LIBRARY_PATH
@@ -2719,7 +2918,7 @@ netbsd*)
 
 newsos6)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   ;;
@@ -2728,58 +2927,68 @@ newsos6)
   version_type=qnx
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
   hardcode_into_libs=yes
   dynamic_linker='ldqnx.so'
   ;;
 
-openbsd*)
+openbsd* | bitrig*)
   version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
+  sys_lib_dlsearch_path_spec=/usr/lib
   need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[[89]] | openbsd2.[[89]].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
+    need_version=no
   else
-    shlibpath_overrides_runpath=yes
+    need_version=yes
   fi
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
   ;;
 
 os2*)
   libname_spec='$name'
-  shrext_cmds=".dll"
+  version_type=windows
+  shrext_cmds=.dll
+  need_version=no
   need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
+  # OS/2 can only load a DLL with a base name of 8 characters or less.
+  soname_spec='`test -n "$os2dllname" && libname="$os2dllname";
+    v=$($ECHO $release$versuffix | tr -d .-);
+    n=$($ECHO $libname | cut -b -$((8 - ${#v})) | tr . _);
+    $ECHO $n$v`$shared_ext'
+  library_names_spec='${libname}_dll.$libext'
   dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
+  shlibpath_var=BEGINLIBPATH
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+  postinstall_cmds='base_file=`basename \$file`~
+    dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; $ECHO \$dlname'\''`~
+    dldir=$destdir/`dirname \$dlpath`~
+    test -d \$dldir || mkdir -p \$dldir~
+    $install_prog $dir/$dlname \$dldir/$dlname~
+    chmod a+x \$dldir/$dlname~
+    if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+      eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+    fi'
+  postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; $ECHO \$dlname'\''`~
+    dlpath=$dir/\$dldll~
+    $RM \$dlpath'
   ;;
 
 osf3* | osf4* | osf5*)
   version_type=osf
   need_lib_prefix=no
   need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='$libname$release$shared_ext$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
   ;;
 
 rdos*)
@@ -2790,8 +2999,8 @@ solaris*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   hardcode_into_libs=yes
@@ -2801,11 +3010,11 @@ solaris*)
 
 sunos4*)
   version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$shared_ext$versuffix'
   finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     need_lib_prefix=no
   fi
   need_version=yes
@@ -2813,8 +3022,8 @@ sunos4*)
 
 sysv4 | sysv4.3*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   case $host_vendor in
     sni)
@@ -2835,24 +3044,24 @@ sysv4 | sysv4.3*)
   ;;
 
 sysv4*MP*)
-  if test -d /usr/nec ;then
+  if test -d /usr/nec; then
     version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
+    library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext'
+    soname_spec='$libname$shared_ext.$major'
     shlibpath_var=LD_LIBRARY_PATH
   fi
   ;;
 
 sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
+  version_type=sco
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=yes
   hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
   else
     sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
@@ -2870,7 +3079,7 @@ tpf*)
   version_type=linux # correct to gnu/linux during the next big refactor
   need_lib_prefix=no
   need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
   shlibpath_var=LD_LIBRARY_PATH
   shlibpath_overrides_runpath=no
   hardcode_into_libs=yes
@@ -2878,8 +3087,8 @@ tpf*)
 
 uts4*)
   version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext'
+  soname_spec='$libname$release$shared_ext$major'
   shlibpath_var=LD_LIBRARY_PATH
   ;;
 
@@ -2888,20 +3097,30 @@ uts4*)
   ;;
 esac
 AC_MSG_RESULT([$dynamic_linker])
-test "$dynamic_linker" = no && can_build_shared=no
+test no = "$dynamic_linker" && can_build_shared=no
 
 variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
 fi
 
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then
+  sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec
 fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+
+if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then
+  sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec
 fi
 
+# remember unaugmented sys_lib_dlsearch_path content for libtool script decls...
+configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec
+
+# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code
+func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH"
+
+# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool
+configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH
+
 _LT_DECL([], [variables_saved_for_relink], [1],
     [Variables whose values should be saved in libtool wrapper scripts and
     restored at link time])
@@ -2934,39 +3153,41 @@ _LT_DECL([], [hardcode_into_libs], [0],
     [Whether we should hardcode library paths into libraries])
 _LT_DECL([], [sys_lib_search_path_spec], [2],
     [Compile-time system search path for libraries])
-_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
-    [Run-time system search path for libraries])
+_LT_DECL([sys_lib_dlsearch_path_spec], [configure_time_dlsearch_path], [2],
+    [Detected run-time system search path for libraries])
+_LT_DECL([], [configure_time_lt_sys_library_path], [2],
+    [Explicit LT_SYS_LIBRARY_PATH set during ./configure time])
 ])# _LT_SYS_DYNAMIC_LINKER
 
 
 # _LT_PATH_TOOL_PREFIX(TOOL)
 # --------------------------
-# find a file program which can recognize shared library
+# find a file program that can recognize shared library
 AC_DEFUN([_LT_PATH_TOOL_PREFIX],
 [m4_require([_LT_DECL_EGREP])dnl
 AC_MSG_CHECKING([for $1])
 AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
 [case $MAGIC_CMD in
 [[\\/*] |  ?:[\\/]*])
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path.
   ;;
 *)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  lt_save_MAGIC_CMD=$MAGIC_CMD
+  lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
 dnl $ac_dummy forces splitting on constant user-supplied paths.
 dnl POSIX.2 word splitting is done only on the output of word expansions,
 dnl not every word.  This closes a longstanding sh security hole.
   ac_dummy="m4_if([$2], , $PATH, [$2])"
   for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
     test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$1; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+    if test -f "$ac_dir/$1"; then
+      lt_cv_path_MAGIC_CMD=$ac_dir/"$1"
       if test -n "$file_magic_test_file"; then
 	case $deplibs_check_method in
 	"file_magic "*)
 	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+	  MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
 	    $EGREP "$file_magic_regex" > /dev/null; then
 	    :
@@ -2989,11 +3210,11 @@ _LT_EOF
       break
     fi
   done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  IFS=$lt_save_ifs
+  MAGIC_CMD=$lt_save_MAGIC_CMD
   ;;
 esac])
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+MAGIC_CMD=$lt_cv_path_MAGIC_CMD
 if test -n "$MAGIC_CMD"; then
   AC_MSG_RESULT($MAGIC_CMD)
 else
@@ -3011,7 +3232,7 @@ dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
 
 # _LT_PATH_MAGIC
 # --------------
-# find a file program which can recognize a shared library
+# find a file program that can recognize a shared library
 m4_defun([_LT_PATH_MAGIC],
 [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
 if test -z "$lt_cv_path_MAGIC_CMD"; then
@@ -3038,16 +3259,16 @@ m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
 AC_ARG_WITH([gnu-ld],
     [AS_HELP_STRING([--with-gnu-ld],
 	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
-    [test "$withval" = no || with_gnu_ld=yes],
+    [test no = "$withval" || with_gnu_ld=yes],
     [with_gnu_ld=no])dnl
 
 ac_prog=ld
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   # Check if gcc -print-prog-name=ld gives a path.
   AC_MSG_CHECKING([for ld used by $CC])
   case $host in
   *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
+    # gcc leaves a trailing carriage return, which upsets mingw
     ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
   *)
     ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
@@ -3061,7 +3282,7 @@ if test "$GCC" = yes; then
       while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
 	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
       done
-      test -z "$LD" && LD="$ac_prog"
+      test -z "$LD" && LD=$ac_prog
       ;;
   "")
     # If it fails, then pretend we aren't using GCC.
@@ -3072,37 +3293,37 @@ if test "$GCC" = yes; then
     with_gnu_ld=unknown
     ;;
   esac
-elif test "$with_gnu_ld" = yes; then
+elif test yes = "$with_gnu_ld"; then
   AC_MSG_CHECKING([for GNU ld])
 else
   AC_MSG_CHECKING([for non-GNU ld])
 fi
 AC_CACHE_VAL(lt_cv_path_LD,
 [if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
   for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
     test -z "$ac_dir" && ac_dir=.
     if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
+      lt_cv_path_LD=$ac_dir/$ac_prog
       # Check to see if the program is GNU ld.  I'd rather use --version,
       # but apparently some variants of GNU ld only accept -v.
       # Break only if it was the GNU/non-GNU ld that we prefer.
       case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
       *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
+	test no != "$with_gnu_ld" && break
 	;;
       *)
-	test "$with_gnu_ld" != yes && break
+	test yes != "$with_gnu_ld" && break
 	;;
       esac
     fi
   done
-  IFS="$lt_save_ifs"
+  IFS=$lt_save_ifs
 else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+  lt_cv_path_LD=$LD # Let the user override the test with a path.
 fi])
-LD="$lt_cv_path_LD"
+LD=$lt_cv_path_LD
 if test -n "$LD"; then
   AC_MSG_RESULT($LD)
 else
@@ -3156,13 +3377,13 @@ esac
 reload_cmds='$LD$reload_flag -o $output$reload_objs'
 case $host_os in
   cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
+    if test yes != "$GCC"; then
       reload_cmds=false
     fi
     ;;
   darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    if test yes = "$GCC"; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib $wl-r -o $output$reload_objs'
     else
       reload_cmds='$LD$reload_flag -o $output$reload_objs'
     fi
@@ -3173,6 +3394,43 @@ _LT_TAGDECL([], [reload_cmds], [2])dnl
 ])# _LT_CMD_RELOAD
 
 
+# _LT_PATH_DD
+# -----------
+# find a working dd
+m4_defun([_LT_PATH_DD],
+[AC_CACHE_CHECK([for a working dd], [ac_cv_path_lt_DD],
+[printf 0123456789abcdef0123456789abcdef >conftest.i
+cat conftest.i conftest.i >conftest2.i
+: ${lt_DD:=$DD}
+AC_PATH_PROGS_FEATURE_CHECK([lt_DD], [dd],
+[if "$ac_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; then
+  cmp -s conftest.i conftest.out \
+  && ac_cv_path_lt_DD="$ac_path_lt_DD" ac_path_lt_DD_found=:
+fi])
+rm -f conftest.i conftest2.i conftest.out])
+])# _LT_PATH_DD
+
+
+# _LT_CMD_TRUNCATE
+# ----------------
+# find command to truncate a binary pipe
+m4_defun([_LT_CMD_TRUNCATE],
+[m4_require([_LT_PATH_DD])
+AC_CACHE_CHECK([how to truncate binary pipes], [lt_cv_truncate_bin],
+[printf 0123456789abcdef0123456789abcdef >conftest.i
+cat conftest.i conftest.i >conftest2.i
+lt_cv_truncate_bin=
+if "$ac_cv_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; then
+  cmp -s conftest.i conftest.out \
+  && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1"
+fi
+rm -f conftest.i conftest2.i conftest.out
+test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q"])
+_LT_DECL([lt_truncate_bin], [lt_cv_truncate_bin], [1],
+  [Command to truncate a binary pipe])
+])# _LT_CMD_TRUNCATE
+
+
 # _LT_CHECK_MAGIC_METHOD
 # ----------------------
 # how to check for library dependencies
@@ -3188,13 +3446,13 @@ lt_cv_deplibs_check_method='unknown'
 # Need to set the preceding variable on all platforms that support
 # interlibrary dependencies.
 # 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
+# 'unknown' -- same as none, but documents that we really don't know.
 # 'pass_all' -- all dependencies passed with no checks.
 # 'test_compile' -- check by making test program.
 # 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
+# that responds to the $file_magic_cmd with a given extended regex.
+# If you have 'file' or equivalent on your system and you're not sure
+# whether 'pass_all' will *always* work, you probably want this one.
 
 case $host_os in
 aix[[4-9]]*)
@@ -3221,8 +3479,7 @@ mingw* | pw32*)
   # Base MSYS/MinGW do not provide the 'file' command needed by
   # func_win32_libid shell function, so use a weaker test based on 'objdump',
   # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
+  if ( file / ) >/dev/null 2>&1; then
     lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
     lt_cv_file_magic_cmd='func_win32_libid'
   else
@@ -3318,8 +3575,8 @@ newos6*)
   lt_cv_deplibs_check_method=pass_all
   ;;
 
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+openbsd* | bitrig*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
     lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
   else
     lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
@@ -3372,6 +3629,9 @@ sysv4 | sysv4.3*)
 tpf*)
   lt_cv_deplibs_check_method=pass_all
   ;;
+os2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
 esac
 ])
 
@@ -3412,33 +3672,38 @@ AC_DEFUN([LT_PATH_NM],
 AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
 [if test -n "$NM"; then
   # Let the user override the test.
-  lt_cv_path_NM="$NM"
+  lt_cv_path_NM=$NM
 else
-  lt_nm_to_check="${ac_tool_prefix}nm"
+  lt_nm_to_check=${ac_tool_prefix}nm
   if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
     lt_nm_to_check="$lt_nm_to_check nm"
   fi
   for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR
     for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+      tmp_nm=$ac_dir/$lt_tmp_nm
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext"; then
 	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
+	# Adding the 'sed 1q' prevents false positives on HP-UX, which says:
 	#   nm: unknown option "B" ignored
 	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
+	# MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty
+	case $build_os in
+	mingw*) lt_bad_file=conftest.nm/nofile ;;
+	*) lt_bad_file=/dev/null ;;
+	esac
+	case `"$tmp_nm" -B $lt_bad_file 2>&1 | sed '1q'` in
+	*$lt_bad_file* | *'Invalid file or object type'*)
 	  lt_cv_path_NM="$tmp_nm -B"
-	  break
+	  break 2
 	  ;;
 	*)
 	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
 	  */dev/null*)
 	    lt_cv_path_NM="$tmp_nm -p"
-	    break
+	    break 2
 	    ;;
 	  *)
 	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
@@ -3449,21 +3714,21 @@ else
 	esac
       fi
     done
-    IFS="$lt_save_ifs"
+    IFS=$lt_save_ifs
   done
   : ${lt_cv_path_NM=no}
 fi])
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
+if test no != "$lt_cv_path_NM"; then
+  NM=$lt_cv_path_NM
 else
   # Didn't find any BSD compatible name lister, look for dumpbin.
   if test -n "$DUMPBIN"; then :
     # Let the user override the test.
   else
     AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    case `$DUMPBIN -symbols -headers /dev/null 2>&1 | sed '1q'` in
     *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
+      DUMPBIN="$DUMPBIN -symbols -headers"
       ;;
     *)
       DUMPBIN=:
@@ -3471,8 +3736,8 @@ else
     esac
   fi
   AC_SUBST([DUMPBIN])
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
+  if test : != "$DUMPBIN"; then
+    NM=$DUMPBIN
   fi
 fi
 test -z "$NM" && NM=nm
@@ -3518,8 +3783,8 @@ lt_cv_sharedlib_from_linklib_cmd,
 
 case $host_os in
 cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
+  # two different shell functions defined in ltmain.sh;
+  # decide which one to use based on capabilities of $DLLTOOL
   case `$DLLTOOL --help 2>&1` in
   *--identify-strict*)
     lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
@@ -3531,7 +3796,7 @@ cygwin* | mingw* | pw32* | cegcc*)
   ;;
 *)
   # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
+  lt_cv_sharedlib_from_linklib_cmd=$ECHO
   ;;
 esac
 ])
@@ -3558,13 +3823,28 @@ AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool
     lt_cv_path_mainfest_tool=yes
   fi
   rm -f conftest*])
-if test "x$lt_cv_path_mainfest_tool" != xyes; then
+if test yes != "$lt_cv_path_mainfest_tool"; then
   MANIFEST_TOOL=:
 fi
 _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
 ])# _LT_PATH_MANIFEST_TOOL
 
 
+# _LT_DLL_DEF_P([FILE])
+# ---------------------
+# True iff FILE is a Windows DLL '.def' file.
+# Keep in sync with func_dll_def_p in the libtool script
+AC_DEFUN([_LT_DLL_DEF_P],
+[dnl
+  test DEF = "`$SED -n dnl
+    -e '\''s/^[[	 ]]*//'\'' dnl Strip leading whitespace
+    -e '\''/^\(;.*\)*$/d'\'' dnl      Delete empty lines and comments
+    -e '\''s/^\(EXPORTS\|LIBRARY\)\([[	 ]].*\)*$/DEF/p'\'' dnl
+    -e q dnl                          Only consider the first "real" line
+    $1`" dnl
+])# _LT_DLL_DEF_P
+
+
 # LT_LIB_M
 # --------
 # check for math library
@@ -3576,11 +3856,11 @@ case $host in
   # These system don't have libm, or don't need it
   ;;
 *-ncr-sysv4.3*)
-  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=-lmw)
   AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
   ;;
 *)
-  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  AC_CHECK_LIB(m, cos, LIBM=-lm)
   ;;
 esac
 AC_SUBST([LIBM])
@@ -3599,7 +3879,7 @@ m4_defun([_LT_COMPILER_NO_RTTI],
 
 _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
 
-if test "$GCC" = yes; then
+if test yes = "$GCC"; then
   case $cc_basename in
   nvcc*)
     _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
@@ -3651,7 +3931,7 @@ cygwin* | mingw* | pw32* | cegcc*)
   symcode='[[ABCDGISTW]]'
   ;;
 hpux*)
-  if test "$host_cpu" = ia64; then
+  if test ia64 = "$host_cpu"; then
     symcode='[[ABCDEGRST]]'
   fi
   ;;
@@ -3684,14 +3964,44 @@ case `$NM -V 2>&1` in
   symcode='[[ABCDGIRSTW]]' ;;
 esac
 
+if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+  # Gets list of data symbols to import.
+  lt_cv_sys_global_symbol_to_import="sed -n -e 's/^I .* \(.*\)$/\1/p'"
+  # Adjust the below global symbol transforms to fixup imported variables.
+  lt_cdecl_hook=" -e 's/^I .* \(.*\)$/extern __declspec(dllimport) char \1;/p'"
+  lt_c_name_hook=" -e 's/^I .* \(.*\)$/  {\"\1\", (void *) 0},/p'"
+  lt_c_name_lib_hook="\
+  -e 's/^I .* \(lib.*\)$/  {\"\1\", (void *) 0},/p'\
+  -e 's/^I .* \(.*\)$/  {\"lib\1\", (void *) 0},/p'"
+else
+  # Disable hooks by default.
+  lt_cv_sys_global_symbol_to_import=
+  lt_cdecl_hook=
+  lt_c_name_hook=
+  lt_c_name_lib_hook=
+fi
+
 # Transform an extracted symbol line into a proper C declaration.
 # Some systems (esp. on ia64) link data and code symbols differently,
 # so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+lt_cv_sys_global_symbol_to_cdecl="sed -n"\
+$lt_cdecl_hook\
+" -e 's/^T .* \(.*\)$/extern int \1();/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/extern char \1;/p'"
 
 # Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address="sed -n"\
+$lt_c_name_hook\
+" -e 's/^: \(.*\) .*$/  {\"\1\", (void *) 0},/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/  {\"\1\", (void *) \&\1},/p'"
+
+# Transform an extracted symbol line into symbol name with lib prefix and
+# symbol address.
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n"\
+$lt_c_name_lib_hook\
+" -e 's/^: \(.*\) .*$/  {\"\1\", (void *) 0},/p'"\
+" -e 's/^$symcode$symcode* .* \(lib.*\)$/  {\"\1\", (void *) \&\1},/p'"\
+" -e 's/^$symcode$symcode* .* \(.*\)$/  {\"lib\1\", (void *) \&\1},/p'"
 
 # Handle CRLF in mingw tool chain
 opt_cr=
@@ -3709,21 +4019,24 @@ for ac_symprfx in "" "_"; do
 
   # Write the raw and C identifiers.
   if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
+    # Fake it for dumpbin and say T for any non-static function,
+    # D for any global variable and I for any imported variable.
     # Also find C++ and __fastcall symbols from MSVC++,
     # which start with @ or ?.
     lt_cv_sys_global_symbol_pipe="$AWK ['"\
 "     {last_section=section; section=\$ 3};"\
 "     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
 "     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     /^ *Symbol name *: /{split(\$ 0,sn,\":\"); si=substr(sn[2],2)};"\
+"     /^ *Type *: code/{print \"T\",si,substr(si,length(prfx))};"\
+"     /^ *Type *: data/{print \"I\",si,substr(si,length(prfx))};"\
 "     \$ 0!~/External *\|/{next};"\
 "     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
 "     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     {f=\"D\"}; \$ 0~/\(\).*\|/{f=\"T\"};"\
+"     {split(\$ 0,a,/\||\r/); split(a[2],s)};"\
+"     s[1]~/^[@?]/{print f,s[1],s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print f,t[1],substr(t[1],length(prfx))}"\
 "     ' prfx=^$ac_symprfx]"
   else
     lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
@@ -3763,11 +4076,11 @@ _LT_EOF
 	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
 	  cat <<_LT_EOF > conftest.$ac_ext
 /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
+#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE
+/* DATA imports from DLLs on WIN32 can't be const, because runtime
    relocations are performed -- see ld's documentation on pseudo-relocs.  */
 # define LT@&t at _DLSYM_CONST
-#elif defined(__osf__)
+#elif defined __osf__
 /* This system does not cope well with relocations in const data.  */
 # define LT@&t at _DLSYM_CONST
 #else
@@ -3793,7 +4106,7 @@ lt__PROGRAM__LTX_preloaded_symbols[[]] =
 {
   { "@PROGRAM@", (void *) 0 },
 _LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  $SED "s/^$symcode$symcode* .* \(.*\)$/  {\"\1\", (void *) \&\1},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
 	  cat <<\_LT_EOF >> conftest.$ac_ext
   {0, (void *) 0}
 };
@@ -3813,9 +4126,9 @@ _LT_EOF
 	  mv conftest.$ac_objext conftstm.$ac_objext
 	  lt_globsym_save_LIBS=$LIBS
 	  lt_globsym_save_CFLAGS=$CFLAGS
-	  LIBS="conftstm.$ac_objext"
+	  LIBS=conftstm.$ac_objext
 	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
-	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+	  if AC_TRY_EVAL(ac_link) && test -s conftest$ac_exeext; then
 	    pipe_works=yes
 	  fi
 	  LIBS=$lt_globsym_save_LIBS
@@ -3836,7 +4149,7 @@ _LT_EOF
   rm -rf conftest* conftst*
 
   # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
+  if test yes = "$pipe_works"; then
     break
   else
     lt_cv_sys_global_symbol_pipe=
@@ -3863,12 +4176,16 @@ _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
     [Take the output of nm and produce a listing of raw symbols and C names])
 _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
     [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_import], [lt_cv_sys_global_symbol_to_import], [1],
+    [Transform the output of nm into a list of symbols to manually relocate])
 _LT_DECL([global_symbol_to_c_name_address],
     [lt_cv_sys_global_symbol_to_c_name_address], [1],
     [Transform the output of nm in a C name address pair])
 _LT_DECL([global_symbol_to_c_name_address_lib_prefix],
     [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
     [Transform the output of nm in a C name address pair when lib prefix is needed])
+_LT_DECL([nm_interface], [lt_cv_nm_interface], [1],
+    [The name lister interface])
 _LT_DECL([], [nm_file_list_spec], [1],
     [Specify filename containing input files for $NM])
 ]) # _LT_CMD_GLOBAL_SYMBOLS
@@ -3884,17 +4201,18 @@ _LT_TAGVAR(lt_prog_compiler_static, $1)=
 
 m4_if([$1], [CXX], [
   # C++ specific cases for pic, static, wl, etc.
-  if test "$GXX" = yes; then
+  if test yes = "$GXX"; then
     _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
     _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
 
     case $host_os in
     aix*)
       # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# AIX 5 now supports IA64 processor
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       fi
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
       ;;
 
     amigaos*)
@@ -3905,8 +4223,8 @@ m4_if([$1], [CXX], [
         ;;
       m68k)
             # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
+            # adding the '-m68020' flag to GCC prevents building anything better,
+            # like '-m68040'.
             _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
         ;;
       esac
@@ -3922,6 +4240,11 @@ m4_if([$1], [CXX], [
       # (--disable-auto-import) libraries
       m4_if([$1], [GCJ], [],
 	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      case $host_os in
+      os2*)
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static'
+	;;
+      esac
       ;;
     darwin* | rhapsody*)
       # PIC is the default on this platform
@@ -3971,7 +4294,7 @@ m4_if([$1], [CXX], [
     case $host_os in
       aix[[4-9]]*)
 	# All AIX code is PIC.
-	if test "$host_cpu" = ia64; then
+	if test ia64 = "$host_cpu"; then
 	  # AIX 5 now supports IA64 processor
 	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
 	else
@@ -4012,14 +4335,14 @@ m4_if([$1], [CXX], [
 	case $cc_basename in
 	  CC*)
 	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    if test "$host_cpu" != ia64; then
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive'
+	    if test ia64 != "$host_cpu"; then
 	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
 	    fi
 	    ;;
 	  aCC*)
 	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+	    _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive'
 	    case $host_cpu in
 	    hppa*64*|ia64*)
 	      # +Z the default
@@ -4056,7 +4379,7 @@ m4_if([$1], [CXX], [
 	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
 	    ;;
 	  ecpc* )
-	    # old Intel C++ for x86_64 which still supported -KPIC.
+	    # old Intel C++ for x86_64, which still supported -KPIC.
 	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
 	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
@@ -4201,17 +4524,18 @@ m4_if([$1], [CXX], [
   fi
 ],
 [
-  if test "$GCC" = yes; then
+  if test yes = "$GCC"; then
     _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
     _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
 
     case $host_os in
       aix*)
       # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# AIX 5 now supports IA64 processor
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       fi
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
       ;;
 
     amigaos*)
@@ -4222,8 +4546,8 @@ m4_if([$1], [CXX], [
         ;;
       m68k)
             # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
+            # adding the '-m68020' flag to GCC prevents building anything better,
+            # like '-m68040'.
             _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
         ;;
       esac
@@ -4240,6 +4564,11 @@ m4_if([$1], [CXX], [
       # (--disable-auto-import) libraries
       m4_if([$1], [GCJ], [],
 	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      case $host_os in
+      os2*)
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static'
+	;;
+      esac
       ;;
 
     darwin* | rhapsody*)
@@ -4310,7 +4639,7 @@ m4_if([$1], [CXX], [
     case $host_os in
     aix*)
       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# AIX 5 now supports IA64 processor
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       else
@@ -4318,11 +4647,30 @@ m4_if([$1], [CXX], [
       fi
       ;;
 
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      case $cc_basename in
+      nagfor*)
+        # NAG Fortran compiler
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      esac
+      ;;
+
     mingw* | cygwin* | pw32* | os2* | cegcc*)
       # This hack is so that the source file can tell whether it is being
       # built for inclusion in a dll (and should export symbols for example).
       m4_if([$1], [GCJ], [],
 	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      case $host_os in
+      os2*)
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-static'
+	;;
+      esac
       ;;
 
     hpux9* | hpux10* | hpux11*)
@@ -4338,7 +4686,7 @@ m4_if([$1], [CXX], [
 	;;
       esac
       # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='$wl-a ${wl}archive'
       ;;
 
     irix5* | irix6* | nonstopux*)
@@ -4349,7 +4697,7 @@ m4_if([$1], [CXX], [
 
     linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
       case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
+      # old Intel for x86_64, which still supported -KPIC.
       ecc*)
 	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
 	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
@@ -4374,6 +4722,12 @@ m4_if([$1], [CXX], [
 	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
 	;;
+      tcc*)
+	# Fabrice Bellard et al's Tiny C Compiler
+	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+	;;
       pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
@@ -4471,7 +4825,7 @@ m4_if([$1], [CXX], [
       ;;
 
     sysv4*MP*)
-      if test -d /usr/nec ;then
+      if test -d /usr/nec; then
 	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
 	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
       fi
@@ -4500,7 +4854,7 @@ m4_if([$1], [CXX], [
   fi
 ])
 case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
+  # For platforms that do not support PIC, -DPIC is meaningless:
   *djgpp*)
     _LT_TAGVAR(lt_prog_compiler_pic, $1)=
     ;;
@@ -4566,17 +4920,21 @@ m4_if([$1], [CXX], [
   case $host_os in
   aix[[4-9]]*)
     # If we're using GNU nm, then we don't want the "-C" option.
-    # -C means demangle to AIX nm, but means don't demangle with GNU nm
-    # Also, AIX nm treats weak defined symbols like other global defined
-    # symbols, whereas GNU nm marks them as "W".
+    # -C means demangle to GNU nm, but means don't demangle to AIX nm.
+    # Without the "-l" option, or with the "-B" option, AIX nm treats
+    # weak defined symbols like other global defined symbols, whereas
+    # GNU nm marks them as "W".
+    # While the 'weak' keyword is ignored in the Export File, we need
+    # it in the Import File for the 'aix-soname' feature, so we have
+    # to replace the "-B" option with "-P" for AIX nm.
     if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols'
     else
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+      _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols'
     fi
     ;;
   pw32*)
-    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+    _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds
     ;;
   cygwin* | mingw* | cegcc*)
     case $cc_basename in
@@ -4625,9 +4983,9 @@ m4_if([$1], [CXX], [
   # included in the symbol list
   _LT_TAGVAR(include_expsyms, $1)=
   # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
+  # it will be wrapped by ' (' and ')$', so one must not match beginning or
+  # end of line.  Example: 'a|bc|.*d.*' will exclude the symbols 'a' and 'bc',
+  # as well as any symbol that contains 'd'.
   _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
   # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
   # platforms (ab)use it in PIC code, but their linkers get confused if
@@ -4643,7 +5001,7 @@ dnl Note also adjust exclude_expsyms for C++ above.
     # FIXME: the MSVC++ port hasn't been tested in a loooong time
     # When not using gcc, we currently assume that we are using
     # Microsoft Visual C++.
-    if test "$GCC" != yes; then
+    if test yes != "$GCC"; then
       with_gnu_ld=no
     fi
     ;;
@@ -4651,7 +5009,7 @@ dnl Note also adjust exclude_expsyms for C++ above.
     # we just hope/assume this is gcc and not c89 (= MSVC++)
     with_gnu_ld=yes
     ;;
-  openbsd*)
+  openbsd* | bitrig*)
     with_gnu_ld=no
     ;;
   linux* | k*bsd*-gnu | gnu*)
@@ -4664,7 +5022,7 @@ dnl Note also adjust exclude_expsyms for C++ above.
   # On some targets, GNU ld is compatible enough with the native linker
   # that we're better off using the native interface for both.
   lt_use_gnu_ld_interface=no
-  if test "$with_gnu_ld" = yes; then
+  if test yes = "$with_gnu_ld"; then
     case $host_os in
       aix*)
 	# The AIX port of GNU ld has always aspired to compatibility
@@ -4686,24 +5044,24 @@ dnl Note also adjust exclude_expsyms for C++ above.
     esac
   fi
 
-  if test "$lt_use_gnu_ld_interface" = yes; then
+  if test yes = "$lt_use_gnu_ld_interface"; then
     # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
+    wlarc='$wl'
 
     # Set some defaults for GNU ld with shared library support. These
     # are reset later if shared libraries are not supported. Putting them
     # here allows them to be overridden if necessary.
     runpath_var=LD_RUN_PATH
-    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
     # ancient GNU ld didn't support --whole-archive et. al.
     if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive'
     else
       _LT_TAGVAR(whole_archive_flag_spec, $1)=
     fi
     supports_anon_versioning=no
-    case `$LD -v 2>&1` in
+    case `$LD -v | $SED -e 's/([^)]\+)\s\+//' 2>&1` in
       *GNU\ gold*) supports_anon_versioning=yes ;;
       *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
       *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
@@ -4716,7 +5074,7 @@ dnl Note also adjust exclude_expsyms for C++ above.
     case $host_os in
     aix[[3-9]]*)
       # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
+      if test ia64 != "$host_cpu"; then
 	_LT_TAGVAR(ld_shlibs, $1)=no
 	cat <<_LT_EOF 1>&2
 
@@ -4735,7 +5093,7 @@ _LT_EOF
       case $host_cpu in
       powerpc)
             # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
             _LT_TAGVAR(archive_expsym_cmds, $1)=''
         ;;
       m68k)
@@ -4751,7 +5109,7 @@ _LT_EOF
 	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
 	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
 	# support --undefined.  This deserves some investigation.  FIXME
-	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
       fi
@@ -4761,7 +5119,7 @@ _LT_EOF
       # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
       # as there is no search path for DLLs.
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols'
       _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
       _LT_TAGVAR(always_export_symbols, $1)=no
       _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
@@ -4769,61 +5127,89 @@ _LT_EOF
       _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
 
       if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	# If the export-symbols file already is a .def file, use it as
+	# is; otherwise, prepend EXPORTS...
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then
+          cp $export_symbols $output_objdir/$soname.def;
+        else
+          echo EXPORTS > $output_objdir/$soname.def;
+          cat $export_symbols >> $output_objdir/$soname.def;
+        fi~
+        $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
       fi
       ;;
 
     haiku*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
       _LT_TAGVAR(link_all_deplibs, $1)=yes
       ;;
 
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      shrext_cmds=.dll
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	prefix_cmds="$SED"~
+	if test EXPORTS = "`$SED 1q $export_symbols`"; then
+	  prefix_cmds="$prefix_cmds -e 1d";
+	fi~
+	prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~
+	cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def'
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      ;;
+
     interix[[3-9]]*)
       _LT_TAGVAR(hardcode_direct, $1)=no
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
       # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
       # Instead, shared libraries are loaded at an image base (0x10000000 by
       # default) and relocated if they conflict, which is a slow very memory
       # consuming and fragmenting process.  To avoid this, we pick a random,
       # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
       # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
       ;;
 
     gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
       tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
+      if test linux-dietlibc = "$host_os"; then
 	case $cc_basename in
 	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
 	esac
       fi
       if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
+	 && test no = "$tmp_diet"
       then
 	tmp_addflag=' $pic_flag'
 	tmp_sharedflag='-shared'
 	case $cc_basename,$host_cpu in
         pgcc*)				# Portland Group C compiler
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  tmp_addflag=' $pic_flag'
 	  ;;
 	pgf77* | pgf90* | pgf95* | pgfortran*)
 					# Portland Group f77 and f90 compilers
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  tmp_addflag=' $pic_flag -Mnomain' ;;
 	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
 	  tmp_addflag=' -i_dynamic' ;;
@@ -4834,42 +5220,47 @@ _LT_EOF
 	lf95*)				# Lahey Fortran 8.1
 	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
 	  tmp_sharedflag='--shared' ;;
+        nagfor*)                        # NAGFOR 5.3
+          tmp_sharedflag='-Wl,-shared' ;;
 	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
 	  tmp_sharedflag='-qmkshrobj'
 	  tmp_addflag= ;;
 	nvcc*)	# Cuda Compiler Driver 2.2
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  _LT_TAGVAR(compiler_needs_object, $1)=yes
 	  ;;
 	esac
 	case `$CC -V 2>&1 | sed 5q` in
 	*Sun\ C*)			# Sun C 5.9
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	  _LT_TAGVAR(compiler_needs_object, $1)=yes
 	  tmp_sharedflag='-G' ;;
 	*Sun\ F*)			# Sun Fortran 8.3
 	  tmp_sharedflag='-G' ;;
 	esac
-	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
 
-        if test "x$supports_anon_versioning" = xyes; then
+        if test yes = "$supports_anon_versioning"; then
           _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	    echo "local: *; };" >> $output_objdir/$libname.ver~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+            cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+            echo "local: *; };" >> $output_objdir/$libname.ver~
+            $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib'
         fi
 
 	case $cc_basename in
+	tcc*)
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='-rdynamic'
+	  ;;
 	xlf* | bgf* | bgxlf* | mpixlf*)
 	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
 	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
 	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
-	  if test "x$supports_anon_versioning" = xyes; then
+	  if test yes = "$supports_anon_versioning"; then
 	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+              cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+              echo "local: *; };" >> $output_objdir/$libname.ver~
+              $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
 	  fi
 	  ;;
 	esac
@@ -4883,8 +5274,8 @@ _LT_EOF
 	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
 	wlarc=
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       fi
       ;;
 
@@ -4902,8 +5293,8 @@ _LT_EOF
 
 _LT_EOF
       elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
       fi
@@ -4915,7 +5306,7 @@ _LT_EOF
 	_LT_TAGVAR(ld_shlibs, $1)=no
 	cat <<_LT_EOF 1>&2
 
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 cannot
 *** reliably create shared libraries on SCO systems.  Therefore, libtool
 *** is disabling shared libraries support.  We urge you to upgrade GNU
 *** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
@@ -4930,9 +5321,9 @@ _LT_EOF
 	  # DT_RUNPATH tag from executables and libraries.  But doing so
 	  # requires that you compile everything twice, which is a pain.
 	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 	  else
 	    _LT_TAGVAR(ld_shlibs, $1)=no
 	  fi
@@ -4949,15 +5340,15 @@ _LT_EOF
 
     *)
       if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
       fi
       ;;
     esac
 
-    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+    if test no = "$_LT_TAGVAR(ld_shlibs, $1)"; then
       runpath_var=
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
       _LT_TAGVAR(export_dynamic_flag_spec, $1)=
@@ -4973,7 +5364,7 @@ _LT_EOF
       # Note: this linker hardcodes the directories in LIBPATH if there
       # are no directories specified by -L.
       _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+      if test yes = "$GCC" && test -z "$lt_prog_compiler_static"; then
 	# Neither direct hardcoding nor static linking is supported with a
 	# broken collect2.
 	_LT_TAGVAR(hardcode_direct, $1)=unsupported
@@ -4981,34 +5372,57 @@ _LT_EOF
       ;;
 
     aix[[4-9]]*)
-      if test "$host_cpu" = ia64; then
+      if test ia64 = "$host_cpu"; then
 	# On IA64, the linker does run time linking by default, so we don't
 	# have to do anything special.
 	aix_use_runtimelinking=no
 	exp_sym_flag='-Bexport'
-	no_entry_flag=""
+	no_entry_flag=
       else
 	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	# Also, AIX nm treats weak defined symbols like other global
-	# defined symbols, whereas GNU nm marks them as "W".
+	# -C means demangle to GNU nm, but means don't demangle to AIX nm.
+	# Without the "-l" option, or with the "-B" option, AIX nm treats
+	# weak defined symbols like other global defined symbols, whereas
+	# GNU nm marks them as "W".
+	# While the 'weak' keyword is ignored in the Export File, we need
+	# it in the Import File for the 'aix-soname' feature, so we have
+	# to replace the "-B" option with "-P" for AIX nm.
 	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { if (\$ 2 == "W") { print \$ 3 " weak" } else { print \$ 3 } } }'\'' | sort -u > $export_symbols'
 	else
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+	  _LT_TAGVAR(export_symbols_cmds, $1)='`func_echo_all $NM | $SED -e '\''s/B\([[^B]]*\)$/P\1/'\''` -PCpgl $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) && ([substr](\$ 1,1,1) != ".")) { if ((\$ 2 == "W") || (\$ 2 == "V") || (\$ 2 == "Z")) { print \$ 1 " weak" } else { print \$ 1 } } }'\'' | sort -u > $export_symbols'
 	fi
 	aix_use_runtimelinking=no
 
 	# Test if we are trying to use run time linking or normal
 	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
+	# have runtime linking enabled, and use it for executables.
+	# For shared libraries, we enable/disable runtime linking
+	# depending on the kind of the shared library created -
+	# when "with_aix_soname,aix_use_runtimelinking" is:
+	# "aix,no"   lib.a(lib.so.V) shared, rtl:no,  for executables
+	# "aix,yes"  lib.so          shared, rtl:yes, for executables
+	#            lib.a           static archive
+	# "both,no"  lib.so.V(shr.o) shared, rtl:yes
+	#            lib.a(lib.so.V) shared, rtl:no,  for executables
+	# "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables
+	#            lib.a(lib.so.V) shared, rtl:no
+	# "svr4,*"   lib.so.V(shr.o) shared, rtl:yes, for executables
+	#            lib.a           static archive
 	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
 	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+	  if (test x-brtl = "x$ld_flag" || test x-Wl,-brtl = "x$ld_flag"); then
 	    aix_use_runtimelinking=yes
 	    break
 	  fi
 	  done
+	  if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then
+	    # With aix-soname=svr4, we create the lib.so.V shared archives only,
+	    # so we don't have lib.a shared libs to link our executables.
+	    # We have to force runtime linking in this case.
+	    aix_use_runtimelinking=yes
+	    LDFLAGS="$LDFLAGS -Wl,-brtl"
+	  fi
 	  ;;
 	esac
 
@@ -5027,13 +5441,21 @@ _LT_EOF
       _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
       _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
       _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+      _LT_TAGVAR(file_list_spec, $1)='$wl-f,'
+      case $with_aix_soname,$aix_use_runtimelinking in
+      aix,*) ;; # traditional, no import file
+      svr4,* | *,yes) # use import file
+	# The Import File defines what to hardcode.
+	_LT_TAGVAR(hardcode_direct, $1)=no
+	_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+	;;
+      esac
 
-      if test "$GCC" = yes; then
+      if test yes = "$GCC"; then
 	case $host_os in aix4.[[012]]|aix4.[[012]].*)
 	# We only want to do this on AIX 4.2 and lower, the check
 	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
+	  collect2name=`$CC -print-prog-name=collect2`
 	  if test -f "$collect2name" &&
 	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
 	  then
@@ -5052,62 +5474,80 @@ _LT_EOF
 	  ;;
 	esac
 	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
+	if test yes = "$aix_use_runtimelinking"; then
+	  shared_flag="$shared_flag "'$wl-G'
 	fi
-	_LT_TAGVAR(link_all_deplibs, $1)=no
+	# Need to ensure runtime linking is disabled for the traditional
+	# shared library, or the linker may eventually find shared libraries
+	# /with/ Import File - we do not want to mix them.
+	shared_flag_aix='-shared'
+	shared_flag_svr4='-shared $wl-G'
       else
 	# not using gcc
-	if test "$host_cpu" = ia64; then
+	if test ia64 = "$host_cpu"; then
 	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
 	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
 	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
+	  if test yes = "$aix_use_runtimelinking"; then
+	    shared_flag='$wl-G'
 	  else
-	    shared_flag='${wl}-bM:SRE'
+	    shared_flag='$wl-bM:SRE'
 	  fi
+	  shared_flag_aix='$wl-bM:SRE'
+	  shared_flag_svr4='$wl-G'
 	fi
       fi
 
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall'
       # It seems that -bexpall does not export symbols beginning with
       # underscore (_), so it is better to generate a list of symbols to export.
       _LT_TAGVAR(always_export_symbols, $1)=yes
-      if test "$aix_use_runtimelinking" = yes; then
+      if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then
 	# Warning - without using the other runtime loading flags (-brtl),
 	# -berok will link without error, but may produce a broken library.
 	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
         # Determine the default libpath from the value encoded in an
         # empty executable.
         _LT_SYS_MODULE_PATH_AIX([$1])
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag
       else
-	if test "$host_cpu" = ia64; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+	if test ia64 = "$host_cpu"; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib'
 	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols"
 	else
 	 # Determine the default libpath from the value encoded in an
 	 # empty executable.
 	 _LT_SYS_MODULE_PATH_AIX([$1])
-	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath"
 	  # Warning - without using the other run time loading flags,
 	  # -berok will link without error, but may produce a broken library.
-	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	  if test "$with_gnu_ld" = yes; then
+	  _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok'
+	  _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok'
+	  if test yes = "$with_gnu_ld"; then
 	    # We only use this code for GNU lds that support --whole-archive.
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive'
 	  else
 	    # Exported symbols can be pulled into shared objects from archives
 	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
 	  fi
 	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d'
+	  # -brtl affects multiple linker settings, -berok does not and is overridden later
+	  compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`'
+	  if test svr4 != "$with_aix_soname"; then
+	    # This is similar to how AIX traditionally builds its shared libraries.
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname'
+	  fi
+	  if test aix != "$with_aix_soname"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# 3 [...]
+	  else
+	    # used by -dlpreopen to get the symbols
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV  $output_objdir/$realname.d/$soname $output_objdir'
+	  fi
+	  _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d'
 	fi
       fi
       ;;
@@ -5116,7 +5556,7 @@ _LT_EOF
       case $host_cpu in
       powerpc)
             # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
             _LT_TAGVAR(archive_expsym_cmds, $1)=''
         ;;
       m68k)
@@ -5146,16 +5586,17 @@ _LT_EOF
 	# Tell ltmain to make .lib files, not .a files.
 	libext=lib
 	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
+	shrext_cmds=.dll
 	# FIXME: Setting linknames here is a bad hack.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	  else
-	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	  fi~
-	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	  linknames='
+	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames='
+	_LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then
+            cp "$export_symbols" "$output_objdir/$soname.def";
+            echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp";
+          else
+            $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp;
+          fi~
+          $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+          linknames='
 	# The linker will not automatically build a static lib if we build a DLL.
 	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
 	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
@@ -5164,18 +5605,18 @@ _LT_EOF
 	# Don't use ranlib
 	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
 	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	  lt_tool_outputfile="@TOOL_OUTPUT@"~
-	  case $lt_outputfile in
-	    *.exe|*.EXE) ;;
-	    *)
-	      lt_outputfile="$lt_outputfile.exe"
-	      lt_tool_outputfile="$lt_tool_outputfile.exe"
-	      ;;
-	  esac~
-	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	    $RM "$lt_outputfile.manifest";
-	  fi'
+          lt_tool_outputfile="@TOOL_OUTPUT@"~
+          case $lt_outputfile in
+            *.exe|*.EXE) ;;
+            *)
+              lt_outputfile=$lt_outputfile.exe
+              lt_tool_outputfile=$lt_tool_outputfile.exe
+              ;;
+          esac~
+          if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then
+            $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+            $RM "$lt_outputfile.manifest";
+          fi'
 	;;
       *)
 	# Assume MSVC wrapper
@@ -5184,7 +5625,7 @@ _LT_EOF
 	# Tell ltmain to make .lib files, not .a files.
 	libext=lib
 	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
+	shrext_cmds=.dll
 	# FIXME: Setting linknames here is a bad hack.
 	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
 	# The linker will automatically build a .lib file if we build a DLL.
@@ -5234,33 +5675,33 @@ _LT_EOF
       ;;
 
     hpux9*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
       else
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
       fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir'
       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
       _LT_TAGVAR(hardcode_direct, $1)=yes
 
       # hardcode_minus_L: Not really in the search PATH,
       # but as the default location of the library.
       _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
       ;;
 
     hpux10*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes,no = "$GCC,$with_gnu_ld"; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
       else
 	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
       fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      if test no = "$with_gnu_ld"; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir'
 	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
 	_LT_TAGVAR(hardcode_direct, $1)=yes
 	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
 	# hardcode_minus_L: Not really in the search PATH,
 	# but as the default location of the library.
 	_LT_TAGVAR(hardcode_minus_L, $1)=yes
@@ -5268,25 +5709,25 @@ _LT_EOF
       ;;
 
     hpux11*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
+      if test yes,no = "$GCC,$with_gnu_ld"; then
 	case $host_cpu in
 	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
 	case $host_cpu in
 	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
 	m4_if($1, [], [
@@ -5294,14 +5735,14 @@ _LT_EOF
 	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
 	  _LT_LINKER_OPTION([if $CC understands -b],
 	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
-	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
+	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
 	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
-	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
+	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
 	  ;;
 	esac
       fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      if test no = "$with_gnu_ld"; then
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir'
 	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
 
 	case $host_cpu in
@@ -5312,7 +5753,7 @@ _LT_EOF
 	*)
 	  _LT_TAGVAR(hardcode_direct, $1)=yes
 	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
 
 	  # hardcode_minus_L: Not really in the search PATH,
 	  # but as the default location of the library.
@@ -5323,16 +5764,16 @@ _LT_EOF
       ;;
 
     irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
 	# Try to use the -exported_symbol ld option, if it does not
 	# work, assume that -exports_file does not work either and
 	# implicitly export all symbols.
 	# This should be the same for all languages, so no per-tag cache variable.
 	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
 	  [lt_cv_irix_exported_symbol],
-	  [save_LDFLAGS="$LDFLAGS"
-	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+	  [save_LDFLAGS=$LDFLAGS
+	   LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null"
 	   AC_LINK_IFELSE(
 	     [AC_LANG_SOURCE(
 	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
@@ -5345,21 +5786,32 @@ _LT_EOF
       end]])])],
 	      [lt_cv_irix_exported_symbol=yes],
 	      [lt_cv_irix_exported_symbol=no])
-           LDFLAGS="$save_LDFLAGS"])
-	if test "$lt_cv_irix_exported_symbol" = yes; then
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+           LDFLAGS=$save_LDFLAGS])
+	if test yes = "$lt_cv_irix_exported_symbol"; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations $wl-exports_file $wl$export_symbols -o $lib'
 	fi
+	_LT_TAGVAR(link_all_deplibs, $1)=no
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -exports_file $export_symbols -o $lib'
       fi
       _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
       _LT_TAGVAR(inherit_rpath, $1)=yes
       _LT_TAGVAR(link_all_deplibs, $1)=yes
       ;;
 
+    linux*)
+      case $cc_basename in
+      tcc*)
+	# Fabrice Bellard et al's Tiny C Compiler
+	_LT_TAGVAR(ld_shlibs, $1)=yes
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	;;
+      esac
+      ;;
+
     netbsd* | netbsdelf*-gnu)
       if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
 	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
@@ -5374,7 +5826,7 @@ _LT_EOF
     newsos6)
       _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
       _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
       ;;
@@ -5382,27 +5834,19 @@ _LT_EOF
     *nto* | *qnx*)
       ;;
 
-    openbsd*)
+    openbsd* | bitrig*)
       if test -f /usr/libexec/ld.so; then
 	_LT_TAGVAR(hardcode_direct, $1)=yes
 	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
 	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then
 	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags $wl-retain-symbols-file,$export_symbols'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
 	else
-	  case $host_os in
-	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
-	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	     ;;
-	   *)
-	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	     ;;
-	  esac
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
 	fi
       else
 	_LT_TAGVAR(ld_shlibs, $1)=no
@@ -5413,33 +5857,53 @@ _LT_EOF
       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
       _LT_TAGVAR(hardcode_minus_L, $1)=yes
       _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      shrext_cmds=.dll
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	$ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	$ECHO EXPORTS >> $output_objdir/$libname.def~
+	prefix_cmds="$SED"~
+	if test EXPORTS = "`$SED 1q $export_symbols`"; then
+	  prefix_cmds="$prefix_cmds -e 1d";
+	fi~
+	prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~
+	cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~
+	$CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	emximp -o $lib $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def'
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
       ;;
 
     osf3*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
       else
 	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
       fi
       _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
       ;;
 
     osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $pic_flag $libobjs $deplibs $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
       else
 	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
 	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+          $CC -shared$allow_undefined_flag $wl-input $wl$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~$RM $lib.exp'
 
 	# Both c and cxx compiler support -rpath directly
 	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
@@ -5450,24 +5914,24 @@ _LT_EOF
 
     solaris*)
       _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	wlarc='$wl'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $wl-z ${wl}text $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags'
 	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+          $CC -shared $pic_flag $wl-z ${wl}text $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
       else
 	case `$CC -V 2>&1` in
 	*"Compilers 5.0"*)
 	  wlarc=''
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$LD -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $linker_flags'
 	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+            $LD -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
 	  ;;
 	*)
-	  wlarc='${wl}'
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	  wlarc='$wl'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h $soname -o $lib $libobjs $deplibs $compiler_flags'
 	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+            $CC -G$allow_undefined_flag -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
 	  ;;
 	esac
       fi
@@ -5477,11 +5941,11 @@ _LT_EOF
       solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
       *)
 	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but understands '-z linker_flag'.  GCC discards it without '$wl',
 	# but is careful enough not to reorder.
 	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+	if test yes = "$GCC"; then
+	  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract'
 	else
 	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
 	fi
@@ -5491,10 +5955,10 @@ _LT_EOF
       ;;
 
     sunos4*)
-      if test "x$host_vendor" = xsequent; then
+      if test sequent = "$host_vendor"; then
 	# Use $CC to link under sequent, because it throws in some extra .o
 	# files that make .init and .fini sections work.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h $soname -o $lib $libobjs $deplibs $compiler_flags'
       else
 	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
       fi
@@ -5543,43 +6007,43 @@ _LT_EOF
       ;;
 
     sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text'
       _LT_TAGVAR(archive_cmds_need_lc, $1)=no
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
       runpath_var='LD_RUN_PATH'
 
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
       ;;
 
     sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
+      # Note: We CANNOT use -z defs as we might desire, because we do not
       # link with -lc, and that would cause any symbols used from libc to
       # always be unresolved, which means just about no library would
       # ever link correctly.  If we're not using GNU ld we use -z text
       # though, which does catch some bad symbols but isn't as heavy-handed
       # as -z defs.
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs'
       _LT_TAGVAR(archive_cmds_need_lc, $1)=no
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir'
       _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
       _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport'
       runpath_var='LD_RUN_PATH'
 
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      if test yes = "$GCC"; then
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
       fi
       ;;
 
@@ -5594,17 +6058,17 @@ _LT_EOF
       ;;
     esac
 
-    if test x$host_vendor = xsni; then
+    if test sni = "$host_vendor"; then
       case $host in
       sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Blargedynsym'
 	;;
       esac
     fi
   fi
 ])
 AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no
 
 _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
 
@@ -5621,7 +6085,7 @@ x|xyes)
   # Assume -lc should be added
   _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
 
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
+  if test yes,yes = "$GCC,$enable_shared"; then
     case $_LT_TAGVAR(archive_cmds, $1) in
     *'~'*)
       # FIXME: we may have to deal with multi-command sequences.
@@ -5701,12 +6165,12 @@ _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
 _LT_TAGDECL([], [hardcode_libdir_separator], [1],
     [Whether we need a single "-rpath" flag with a separated argument])
 _LT_TAGDECL([], [hardcode_direct], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes
     DIR into the resulting binary])
 _LT_TAGDECL([], [hardcode_direct_absolute], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes
     DIR into the resulting binary and the resulting library dependency is
-    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    "absolute", i.e impossible to change by setting $shlibpath_var if the
     library is relocated])
 _LT_TAGDECL([], [hardcode_minus_L], [0],
     [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
@@ -5747,10 +6211,10 @@ dnl    [Compiler flag to generate thread safe objects])
 # ------------------------
 # Ensure that the configuration variables for a C compiler are suitably
 # defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
+# the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_C_CONFIG],
 [m4_require([_LT_DECL_EGREP])dnl
-lt_save_CC="$CC"
+lt_save_CC=$CC
 AC_LANG_PUSH(C)
 
 # Source file extension for C test sources.
@@ -5790,18 +6254,18 @@ if test -n "$compiler"; then
   LT_SYS_DLOPEN_SELF
   _LT_CMD_STRIPLIB
 
-  # Report which library types will actually be built
+  # Report what library types will actually be built
   AC_MSG_CHECKING([if libtool supports shared libraries])
   AC_MSG_RESULT([$can_build_shared])
 
   AC_MSG_CHECKING([whether to build shared libraries])
-  test "$can_build_shared" = "no" && enable_shared=no
+  test no = "$can_build_shared" && enable_shared=no
 
   # On AIX, shared libraries and static libraries use the same namespace, and
   # are all built from PIC.
   case $host_os in
   aix3*)
-    test "$enable_shared" = yes && enable_static=no
+    test yes = "$enable_shared" && enable_static=no
     if test -n "$RANLIB"; then
       archive_cmds="$archive_cmds~\$RANLIB \$lib"
       postinstall_cmds='$RANLIB $lib'
@@ -5809,8 +6273,12 @@ if test -n "$compiler"; then
     ;;
 
   aix[[4-9]]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
+    if test ia64 != "$host_cpu"; then
+      case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in
+      yes,aix,yes) ;;			# shared object as lib.so file only
+      yes,svr4,*) ;;			# shared object as lib.so archive member only
+      yes,*) enable_static=no ;;	# shared object in lib.a archive as well
+      esac
     fi
     ;;
   esac
@@ -5818,13 +6286,13 @@ if test -n "$compiler"; then
 
   AC_MSG_CHECKING([whether to build static libraries])
   # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
+  test yes = "$enable_shared" || enable_static=yes
   AC_MSG_RESULT([$enable_static])
 
   _LT_CONFIG($1)
 fi
 AC_LANG_POP
-CC="$lt_save_CC"
+CC=$lt_save_CC
 ])# _LT_LANG_C_CONFIG
 
 
@@ -5832,14 +6300,14 @@ CC="$lt_save_CC"
 # --------------------------
 # Ensure that the configuration variables for a C++ compiler are suitably
 # defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
+# the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_CXX_CONFIG],
 [m4_require([_LT_FILEUTILS_DEFAULTS])dnl
 m4_require([_LT_DECL_EGREP])dnl
 m4_require([_LT_PATH_MANIFEST_TOOL])dnl
-if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
-    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" != "Xg++"))) ; then
+if test -n "$CXX" && ( test no != "$CXX" &&
+    ( (test g++ = "$CXX" && `g++ -v >/dev/null 2>&1` ) ||
+    (test g++ != "$CXX"))); then
   AC_PROG_CXXCPP
 else
   _lt_caught_CXX_error=yes
@@ -5881,7 +6349,7 @@ _LT_TAGVAR(objext, $1)=$objext
 # the CXX compiler isn't working.  Some variables (like enable_shared)
 # are currently assumed to apply to all compilers on this platform,
 # and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_caught_CXX_error" != yes; then
+if test yes != "$_lt_caught_CXX_error"; then
   # Code to be used in simple compile tests
   lt_simple_compile_test_code="int some_variable = 0;"
 
@@ -5923,35 +6391,35 @@ if test "$_lt_caught_CXX_error" != yes; then
   if test -n "$compiler"; then
     # We don't want -fno-exception when compiling C++ code, so set the
     # no_builtin_flag separately
-    if test "$GXX" = yes; then
+    if test yes = "$GXX"; then
       _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
     else
       _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
     fi
 
-    if test "$GXX" = yes; then
+    if test yes = "$GXX"; then
       # Set up default GNU C++ configuration
 
       LT_PATH_LD
 
       # Check if GNU C++ uses GNU ld as the underlying linker, since the
       # archiving commands below assume that GNU ld is being used.
-      if test "$with_gnu_ld" = yes; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      if test yes = "$with_gnu_ld"; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
 
         # If archive_cmds runs LD, not CC, wlarc should be empty
         # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
         #     investigate it a little bit more. (MM)
-        wlarc='${wl}'
+        wlarc='$wl'
 
         # ancient GNU ld didn't support --whole-archive et. al.
         if eval "`$CC -print-prog-name=ld` --help 2>&1" |
 	  $GREP 'no-whole-archive' > /dev/null; then
-          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive'
         else
           _LT_TAGVAR(whole_archive_flag_spec, $1)=
         fi
@@ -5987,18 +6455,30 @@ if test "$_lt_caught_CXX_error" != yes; then
         _LT_TAGVAR(ld_shlibs, $1)=no
         ;;
       aix[[4-9]]*)
-        if test "$host_cpu" = ia64; then
+        if test ia64 = "$host_cpu"; then
           # On IA64, the linker does run time linking by default, so we don't
           # have to do anything special.
           aix_use_runtimelinking=no
           exp_sym_flag='-Bexport'
-          no_entry_flag=""
+          no_entry_flag=
         else
           aix_use_runtimelinking=no
 
           # Test if we are trying to use run time linking or normal
           # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-          # need to do runtime linking.
+          # have runtime linking enabled, and use it for executables.
+          # For shared libraries, we enable/disable runtime linking
+          # depending on the kind of the shared library created -
+          # when "with_aix_soname,aix_use_runtimelinking" is:
+          # "aix,no"   lib.a(lib.so.V) shared, rtl:no,  for executables
+          # "aix,yes"  lib.so          shared, rtl:yes, for executables
+          #            lib.a           static archive
+          # "both,no"  lib.so.V(shr.o) shared, rtl:yes
+          #            lib.a(lib.so.V) shared, rtl:no,  for executables
+          # "both,yes" lib.so.V(shr.o) shared, rtl:yes, for executables
+          #            lib.a(lib.so.V) shared, rtl:no
+          # "svr4,*"   lib.so.V(shr.o) shared, rtl:yes, for executables
+          #            lib.a           static archive
           case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
 	    for ld_flag in $LDFLAGS; do
 	      case $ld_flag in
@@ -6008,6 +6488,13 @@ if test "$_lt_caught_CXX_error" != yes; then
 	        ;;
 	      esac
 	    done
+	    if test svr4,no = "$with_aix_soname,$aix_use_runtimelinking"; then
+	      # With aix-soname=svr4, we create the lib.so.V shared archives only,
+	      # so we don't have lib.a shared libs to link our executables.
+	      # We have to force runtime linking in this case.
+	      aix_use_runtimelinking=yes
+	      LDFLAGS="$LDFLAGS -Wl,-brtl"
+	    fi
 	    ;;
           esac
 
@@ -6026,13 +6513,21 @@ if test "$_lt_caught_CXX_error" != yes; then
         _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
         _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
         _LT_TAGVAR(link_all_deplibs, $1)=yes
-        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+        _LT_TAGVAR(file_list_spec, $1)='$wl-f,'
+        case $with_aix_soname,$aix_use_runtimelinking in
+        aix,*) ;;	# no import file
+        svr4,* | *,yes) # use import file
+          # The Import File defines what to hardcode.
+          _LT_TAGVAR(hardcode_direct, $1)=no
+          _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+          ;;
+        esac
 
-        if test "$GXX" = yes; then
+        if test yes = "$GXX"; then
           case $host_os in aix4.[[012]]|aix4.[[012]].*)
           # We only want to do this on AIX 4.2 and lower, the check
           # below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
+	  collect2name=`$CC -print-prog-name=collect2`
 	  if test -f "$collect2name" &&
 	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
 	  then
@@ -6050,64 +6545,84 @@ if test "$_lt_caught_CXX_error" != yes; then
 	  fi
           esac
           shared_flag='-shared'
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag="$shared_flag "'${wl}-G'
+	  if test yes = "$aix_use_runtimelinking"; then
+	    shared_flag=$shared_flag' $wl-G'
 	  fi
+	  # Need to ensure runtime linking is disabled for the traditional
+	  # shared library, or the linker may eventually find shared libraries
+	  # /with/ Import File - we do not want to mix them.
+	  shared_flag_aix='-shared'
+	  shared_flag_svr4='-shared $wl-G'
         else
           # not using gcc
-          if test "$host_cpu" = ia64; then
+          if test ia64 = "$host_cpu"; then
 	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
 	  # chokes on -Wl,-G. The following line is correct:
 	  shared_flag='-G'
           else
-	    if test "$aix_use_runtimelinking" = yes; then
-	      shared_flag='${wl}-G'
+	    if test yes = "$aix_use_runtimelinking"; then
+	      shared_flag='$wl-G'
 	    else
-	      shared_flag='${wl}-bM:SRE'
+	      shared_flag='$wl-bM:SRE'
 	    fi
+	    shared_flag_aix='$wl-bM:SRE'
+	    shared_flag_svr4='$wl-G'
           fi
         fi
 
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-bexpall'
         # It seems that -bexpall does not export symbols beginning with
         # underscore (_), so it is better to generate a list of symbols to
 	# export.
         _LT_TAGVAR(always_export_symbols, $1)=yes
-        if test "$aix_use_runtimelinking" = yes; then
+	if test aix,yes = "$with_aix_soname,$aix_use_runtimelinking"; then
           # Warning - without using the other runtime loading flags (-brtl),
           # -berok will link without error, but may produce a broken library.
-          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # The "-G" linker flag allows undefined symbols.
+          _LT_TAGVAR(no_undefined_flag, $1)='-bernotok'
           # Determine the default libpath from the value encoded in an empty
           # executable.
           _LT_SYS_MODULE_PATH_AIX([$1])
-          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath"
 
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs $wl'$no_entry_flag' $compiler_flags `if test -n "$allow_undefined_flag"; then func_echo_all "$wl$allow_undefined_flag"; else :; fi` $wl'$exp_sym_flag:\$export_symbols' '$shared_flag
         else
-          if test "$host_cpu" = ia64; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+          if test ia64 = "$host_cpu"; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $libdir:/usr/lib:/lib'
 	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\$wl$no_entry_flag"' $compiler_flags $wl$allow_undefined_flag '"\$wl$exp_sym_flag:\$export_symbols"
           else
 	    # Determine the default libpath from the value encoded in an
 	    # empty executable.
 	    _LT_SYS_MODULE_PATH_AIX([$1])
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-blibpath:$libdir:'"$aix_libpath"
 	    # Warning - without using the other run time loading flags,
 	    # -berok will link without error, but may produce a broken library.
-	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	    if test "$with_gnu_ld" = yes; then
+	    _LT_TAGVAR(no_undefined_flag, $1)=' $wl-bernotok'
+	    _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-berok'
+	    if test yes = "$with_gnu_ld"; then
 	      # We only use this code for GNU lds that support --whole-archive.
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive'
 	    else
 	      # Exported symbols can be pulled into shared objects from archives
 	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
 	    fi
 	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	    # This is similar to how AIX traditionally builds its shared
-	    # libraries.
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$RM -r $output_objdir/$realname.d~$MKDIR $output_objdir/$realname.d'
+	    # -brtl affects multiple linker settings, -berok does not and is overridden later
+	    compiler_flags_filtered='`func_echo_all "$compiler_flags " | $SED -e "s%-brtl\\([[, ]]\\)%-berok\\1%g"`'
+	    if test svr4 != "$with_aix_soname"; then
+	      # This is similar to how AIX traditionally builds its shared
+	      # libraries. Need -bnortl late, we may have -brtl in LDFLAGS.
+	      _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_aix' -o $output_objdir/$realname.d/$soname $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$realname.d/$soname'
+	    fi
+	    if test aix != "$with_aix_soname"; then
+	      _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$CC '$shared_flag_svr4' -o $output_objdir/$realname.d/$shared_archive_member_spec.o $libobjs $deplibs $wl-bnoentry '$compiler_flags_filtered'$wl-bE:$export_symbols$allow_undefined_flag~$STRIP -e $output_objdir/$realname.d/$shared_archive_member_spec.o~( func_echo_all "#! $soname($shared_archive_member_spec.o)"; if test shr_64 = "$shared_archive_member_spec"; then func_echo_all "# 64"; else func_echo_all "# [...]
+	    else
+	      # used by -dlpreopen to get the symbols
+	      _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$MV  $output_objdir/$realname.d/$soname $output_objdir'
+	    fi
+	    _LT_TAGVAR(archive_expsym_cmds, $1)="$_LT_TAGVAR(archive_expsym_cmds, $1)"'~$RM -r $output_objdir/$realname.d'
           fi
         fi
         ;;
@@ -6117,7 +6632,7 @@ if test "$_lt_caught_CXX_error" != yes; then
 	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
 	  # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
 	  # support --undefined.  This deserves some investigation.  FIXME
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
 	else
 	  _LT_TAGVAR(ld_shlibs, $1)=no
 	fi
@@ -6145,57 +6660,58 @@ if test "$_lt_caught_CXX_error" != yes; then
 	  # Tell ltmain to make .lib files, not .a files.
 	  libext=lib
 	  # Tell ltmain to make .dll files, not .so files.
-	  shrext_cmds=".dll"
+	  shrext_cmds=.dll
 	  # FIXME: Setting linknames here is a bad hack.
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	    else
-	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	    fi~
-	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	    linknames='
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames='
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then
+              cp "$export_symbols" "$output_objdir/$soname.def";
+              echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp";
+            else
+              $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp;
+            fi~
+            $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
+            linknames='
 	  # The linker will not automatically build a static lib if we build a DLL.
 	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
 	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
 	  # Don't use ranlib
 	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
 	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	    lt_tool_outputfile="@TOOL_OUTPUT@"~
-	    case $lt_outputfile in
-	      *.exe|*.EXE) ;;
-	      *)
-		lt_outputfile="$lt_outputfile.exe"
-		lt_tool_outputfile="$lt_tool_outputfile.exe"
-		;;
-	    esac~
-	    func_to_tool_file "$lt_outputfile"~
-	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	      $RM "$lt_outputfile.manifest";
-	    fi'
+            lt_tool_outputfile="@TOOL_OUTPUT@"~
+            case $lt_outputfile in
+              *.exe|*.EXE) ;;
+              *)
+                lt_outputfile=$lt_outputfile.exe
+                lt_tool_outputfile=$lt_tool_outputfile.exe
+                ;;
+            esac~
+            func_to_tool_file "$lt_outputfile"~
+            if test : != "$MANIFEST_TOOL" && test -f "$lt_outputfile.manifest"; then
+              $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
+              $RM "$lt_outputfile.manifest";
+            fi'
 	  ;;
 	*)
 	  # g++
 	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
 	  # as there is no search path for DLLs.
 	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
+	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-all-symbols'
 	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
 	  _LT_TAGVAR(always_export_symbols, $1)=no
 	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
 
 	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	    # If the export-symbols file already is a .def file (1st line
-	    # is EXPORTS), use it as is; otherwise, prepend...
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      cp $export_symbols $output_objdir/$soname.def;
-	    else
-	      echo EXPORTS > $output_objdir/$soname.def;
-	      cat $export_symbols >> $output_objdir/$soname.def;
-	    fi~
-	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+	    # If the export-symbols file already is a .def file, use it as
+	    # is; otherwise, prepend EXPORTS...
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then
+              cp $export_symbols $output_objdir/$soname.def;
+            else
+              echo EXPORTS > $output_objdir/$soname.def;
+              cat $export_symbols >> $output_objdir/$soname.def;
+            fi~
+            $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
 	  else
 	    _LT_TAGVAR(ld_shlibs, $1)=no
 	  fi
@@ -6206,6 +6722,34 @@ if test "$_lt_caught_CXX_error" != yes; then
         _LT_DARWIN_LINKER_FEATURES($1)
 	;;
 
+      os2*)
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+	_LT_TAGVAR(hardcode_minus_L, $1)=yes
+	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+	shrext_cmds=.dll
+	_LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	  $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	  $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	  $ECHO EXPORTS >> $output_objdir/$libname.def~
+	  emxexp $libobjs | $SED /"_DLL_InitTerm"/d >> $output_objdir/$libname.def~
+	  $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	  emximp -o $lib $output_objdir/$libname.def'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='$ECHO "LIBRARY ${soname%$shared_ext} INITINSTANCE TERMINSTANCE" > $output_objdir/$libname.def~
+	  $ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~
+	  $ECHO "DATA MULTIPLE NONSHARED" >> $output_objdir/$libname.def~
+	  $ECHO EXPORTS >> $output_objdir/$libname.def~
+	  prefix_cmds="$SED"~
+	  if test EXPORTS = "`$SED 1q $export_symbols`"; then
+	    prefix_cmds="$prefix_cmds -e 1d";
+	  fi~
+	  prefix_cmds="$prefix_cmds -e \"s/^\(.*\)$/_\1/g\""~
+	  cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~
+	  $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~
+	  emximp -o $lib $output_objdir/$libname.def'
+	_LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def'
+	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+	;;
+
       dgux*)
         case $cc_basename in
           ec++*)
@@ -6241,14 +6785,14 @@ if test "$_lt_caught_CXX_error" != yes; then
         ;;
 
       haiku*)
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
         _LT_TAGVAR(link_all_deplibs, $1)=yes
         ;;
 
       hpux9*)
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir'
         _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
         _LT_TAGVAR(hardcode_direct, $1)=yes
         _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
 				             # but as the default
@@ -6260,7 +6804,7 @@ if test "$_lt_caught_CXX_error" != yes; then
             _LT_TAGVAR(ld_shlibs, $1)=no
             ;;
           aCC*)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
             # Commands to make compiler produce verbose output that lists
             # what "hidden" libraries, object files and flags are used when
             # linking a shared library.
@@ -6269,11 +6813,11 @@ if test "$_lt_caught_CXX_error" != yes; then
             # explicitly linking system object files so we need to strip them
             # from the output so that they don't get included in the library
             # dependencies.
-            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
             ;;
           *)
-            if test "$GXX" = yes; then
-              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            if test yes = "$GXX"; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag $wl+b $wl$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test "x$output_objdir/$soname" = "x$lib" || mv $output_objdir/$soname $lib'
             else
               # FIXME: insert proper C++ library support
               _LT_TAGVAR(ld_shlibs, $1)=no
@@ -6283,15 +6827,15 @@ if test "$_lt_caught_CXX_error" != yes; then
         ;;
 
       hpux10*|hpux11*)
-        if test $with_gnu_ld = no; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        if test no = "$with_gnu_ld"; then
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl+b $wl$libdir'
 	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
 
           case $host_cpu in
             hppa*64*|ia64*)
               ;;
             *)
-	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
               ;;
           esac
         fi
@@ -6317,13 +6861,13 @@ if test "$_lt_caught_CXX_error" != yes; then
           aCC*)
 	    case $host_cpu in
 	      hppa*64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	        ;;
 	      ia64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	        ;;
 	      *)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -b $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	        ;;
 	    esac
 	    # Commands to make compiler produce verbose output that lists
@@ -6334,20 +6878,20 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # explicitly linking system object files so we need to strip them
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 	    ;;
           *)
-	    if test "$GXX" = yes; then
-	      if test $with_gnu_ld = no; then
+	    if test yes = "$GXX"; then
+	      if test no = "$with_gnu_ld"; then
 	        case $host_cpu in
 	          hppa*64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC $wl+h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	            ;;
 	          ia64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	            ;;
 	          *)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag $wl+h $wl$soname $wl+b $wl$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	            ;;
 	        esac
 	      fi
@@ -6362,22 +6906,22 @@ if test "$_lt_caught_CXX_error" != yes; then
       interix[[3-9]]*)
 	_LT_TAGVAR(hardcode_direct, $1)=no
 	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
 	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
 	# Instead, shared libraries are loaded at an image base (0x10000000 by
 	# default) and relocated if they conflict, which is a slow very memory
 	# consuming and fragmenting process.  To avoid this, we pick a random,
 	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
 	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-h,$soname $wl--retain-symbols-file,$output_objdir/$soname.expsym $wl--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
 	;;
       irix5* | irix6*)
         case $cc_basename in
           CC*)
 	    # SGI C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
 
 	    # Archives containing C++ object files must be created using
 	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
@@ -6386,17 +6930,17 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
 	    ;;
           *)
-	    if test "$GXX" = yes; then
-	      if test "$with_gnu_ld" = no; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	    if test yes = "$GXX"; then
+	      if test no = "$with_gnu_ld"; then
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
 	      else
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` -o $lib'
 	      fi
 	    fi
 	    _LT_TAGVAR(link_all_deplibs, $1)=yes
 	    ;;
         esac
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
         _LT_TAGVAR(hardcode_libdir_separator, $1)=:
         _LT_TAGVAR(inherit_rpath, $1)=yes
         ;;
@@ -6409,8 +6953,8 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # KCC will only create a shared library if the output file
 	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
 	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib $wl-retain-symbols-file,$export_symbols; mv \$templib $lib'
 	    # Commands to make compiler produce verbose output that lists
 	    # what "hidden" libraries, object files and flags are used when
 	    # linking a shared library.
@@ -6419,10 +6963,10 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # explicitly linking system object files so we need to strip them
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
 
 	    # Archives containing C++ object files must be created using
 	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
@@ -6436,59 +6980,59 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # earlier do not add the objects themselves.
 	    case `$CC -V 2>&1` in
 	      *"Version 7."*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 		;;
 	      *)  # Version 8.0 or newer
 	        tmp_idyn=
 	        case $host_cpu in
 		  ia64*) tmp_idyn=' -i_dynamic';;
 		esac
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 		;;
 	    esac
 	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive$convenience $wl--no-whole-archive'
 	    ;;
           pgCC* | pgcpp*)
             # Portland Group C++ compiler
 	    case `$CC -V` in
 	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
 	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
-		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
+               rm -rf $tpldir~
+               $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+               compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
 	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
-		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
-		$RANLIB $oldlib'
+                rm -rf $tpldir~
+                $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+                $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
+                $RANLIB $oldlib'
 	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+                rm -rf $tpldir~
+                $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+                $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib'
 	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+                rm -rf $tpldir~
+                $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+                $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 	      ;;
 	    *) # Version 6 and above use weak symbols
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib'
 	      ;;
 	    esac
 
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl--rpath $wl$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
             ;;
 	  cxx*)
 	    # Compaq C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname  -o $lib $wl-retain-symbols-file $wl$export_symbols'
 
 	    runpath_var=LD_RUN_PATH
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
@@ -6502,18 +7046,18 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # explicitly linking system object files so we need to strip them
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
 	    ;;
 	  xl* | mpixl* | bgxl*)
 	    # IBM XL 8.0 on PPC, with GNU ld
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    if test "x$supports_anon_versioning" = xyes; then
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl--export-dynamic'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib'
+	    if test yes = "$supports_anon_versioning"; then
 	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-		echo "local: *; };" >> $output_objdir/$libname.ver~
-		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+                cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+                echo "local: *; };" >> $output_objdir/$libname.ver~
+                $CC -qmkshrobj $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-version-script $wl$output_objdir/$libname.ver -o $lib'
 	    fi
 	    ;;
 	  *)
@@ -6521,10 +7065,10 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    *Sun\ C*)
 	      # Sun C++ 5.9
 	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+	      _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file $wl$export_symbols'
 	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` $wl--no-whole-archive'
 	      _LT_TAGVAR(compiler_needs_object, $1)=yes
 
 	      # Not sure whether something based on
@@ -6582,22 +7126,17 @@ if test "$_lt_caught_CXX_error" != yes; then
         _LT_TAGVAR(ld_shlibs, $1)=yes
 	;;
 
-      openbsd2*)
-        # C++ shared libraries are fairly broken
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      openbsd*)
+      openbsd* | bitrig*)
 	if test -f /usr/libexec/ld.so; then
 	  _LT_TAGVAR(hardcode_direct, $1)=yes
 	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
 	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
 	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
+	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`"; then
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-retain-symbols-file,$export_symbols -o $lib'
+	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-E'
+	    _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive'
 	  fi
 	  output_verbose_link_cmd=func_echo_all
 	else
@@ -6613,9 +7152,9 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # KCC will only create a shared library if the output file
 	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
 	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\$tempext\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
 
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath,$libdir'
 	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
 
 	    # Archives containing C++ object files must be created using
@@ -6633,17 +7172,17 @@ if test "$_lt_caught_CXX_error" != yes; then
           cxx*)
 	    case $host in
 	      osf3*)
-	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	        _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $soname `test -n "$verstring" && func_echo_all "$wl-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
+	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
 		;;
 	      *)
 	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib'
 	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
-	          echo "-hidden">> $lib.exp~
-	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
-	          $RM $lib.exp'
+                  echo "-hidden">> $lib.exp~
+                  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname $wl-input $wl$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry $output_objdir/so_locations -o $lib~
+                  $RM $lib.exp'
 	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
 		;;
 	    esac
@@ -6658,21 +7197,21 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # explicitly linking system object files so we need to strip them
 	    # from the output so that they don't get included in the library
 	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
+	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
 	    ;;
 	  *)
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+	    if test yes,no = "$GXX,$with_gnu_ld"; then
+	      _LT_TAGVAR(allow_undefined_flag, $1)=' $wl-expect_unresolved $wl\*'
 	      case $host in
 	        osf3*)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
 		  ;;
 	        *)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-msym $wl-soname $wl$soname `test -n "$verstring" && func_echo_all "$wl-set_version $wl$verstring"` $wl-update_registry $wl$output_objdir/so_locations -o $lib'
 		  ;;
 	      esac
 
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir'
 	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
 
 	      # Commands to make compiler produce verbose output that lists
@@ -6718,9 +7257,9 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    # Sun C++ 4.2, 5.x and Centerline C++
             _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
 	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G$allow_undefined_flag -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
 	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+              $CC -G$allow_undefined_flag $wl-M $wl$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
 
 	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
 	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
@@ -6728,7 +7267,7 @@ if test "$_lt_caught_CXX_error" != yes; then
 	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
 	      *)
 		# The compiler driver will combine and reorder linker options,
-		# but understands `-z linker_flag'.
+		# but understands '-z linker_flag'.
 	        # Supported since Solaris 2.6 (maybe 2.5.1?)
 		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
 	        ;;
@@ -6745,30 +7284,30 @@ if test "$_lt_caught_CXX_error" != yes; then
 	    ;;
           gcx*)
 	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib'
 
 	    # The C++ compiler must be used to create the archive.
 	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
 	    ;;
           *)
 	    # GNU C++ compiler with Solaris linker
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+	    if test yes,no = "$GXX,$with_gnu_ld"; then
+	      _LT_TAGVAR(no_undefined_flag, $1)=' $wl-z ${wl}defs'
 	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib'
 	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+                  $CC -shared $pic_flag -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
 
 	        # Commands to make compiler produce verbose output that lists
 	        # what "hidden" libraries, object files and flags are used when
 	        # linking a shared library.
 	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 	      else
-	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
+	        # g++ 2.7 appears to require '-G' NOT '-shared' on this
 	        # platform.
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags $wl-h $wl$soname -o $lib'
 	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+                  $CC -G -nostdlib $wl-M $wl$lib.exp $wl-h $wl$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
 
 	        # Commands to make compiler produce verbose output that lists
 	        # what "hidden" libraries, object files and flags are used when
@@ -6776,11 +7315,11 @@ if test "$_lt_caught_CXX_error" != yes; then
 	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
 	      fi
 
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $wl$libdir'
 	      case $host_os in
 		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
 		*)
-		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+		  _LT_TAGVAR(whole_archive_flag_spec, $1)='$wl-z ${wl}allextract$convenience $wl-z ${wl}defaultextract'
 		  ;;
 	      esac
 	    fi
@@ -6789,52 +7328,52 @@ if test "$_lt_caught_CXX_error" != yes; then
         ;;
 
     sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text'
       _LT_TAGVAR(archive_cmds_need_lc, $1)=no
       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
       runpath_var='LD_RUN_PATH'
 
       case $cc_basename in
         CC*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
       esac
       ;;
 
       sysv5* | sco3.2v5* | sco5v6*)
-	# Note: We can NOT use -z defs as we might desire, because we do not
+	# Note: We CANNOT use -z defs as we might desire, because we do not
 	# link with -lc, and that would cause any symbols used from libc to
 	# always be unresolved, which means just about no library would
 	# ever link correctly.  If we're not using GNU ld we use -z text
 	# though, which does catch some bad symbols but isn't as heavy-handed
 	# as -z defs.
-	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+	_LT_TAGVAR(no_undefined_flag, $1)='$wl-z,text'
+	_LT_TAGVAR(allow_undefined_flag, $1)='$wl-z,nodefs'
 	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
 	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R,$libdir'
 	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
 	_LT_TAGVAR(link_all_deplibs, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+	_LT_TAGVAR(export_dynamic_flag_spec, $1)='$wl-Bexport'
 	runpath_var='LD_RUN_PATH'
 
 	case $cc_basename in
           CC*)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -G $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
 	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
-	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
+              '"$_LT_TAGVAR(old_archive_cmds, $1)"
 	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
-	      '"$_LT_TAGVAR(reload_cmds, $1)"
+              '"$_LT_TAGVAR(reload_cmds, $1)"
 	    ;;
 	  *)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $wl-Bexport:$export_symbols $wl-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
 	    ;;
 	esac
       ;;
@@ -6865,10 +7404,10 @@ if test "$_lt_caught_CXX_error" != yes; then
     esac
 
     AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+    test no = "$_LT_TAGVAR(ld_shlibs, $1)" && can_build_shared=no
 
-    _LT_TAGVAR(GCC, $1)="$GXX"
-    _LT_TAGVAR(LD, $1)="$LD"
+    _LT_TAGVAR(GCC, $1)=$GXX
+    _LT_TAGVAR(LD, $1)=$LD
 
     ## CAVEAT EMPTOR:
     ## There is no encapsulation within the following macros, do not change
@@ -6895,7 +7434,7 @@ if test "$_lt_caught_CXX_error" != yes; then
   lt_cv_path_LD=$lt_save_path_LD
   lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
   lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
-fi # test "$_lt_caught_CXX_error" != yes
+fi # test yes != "$_lt_caught_CXX_error"
 
 AC_LANG_POP
 ])# _LT_LANG_CXX_CONFIG
@@ -6917,13 +7456,14 @@ AC_REQUIRE([_LT_DECL_SED])
 AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
 func_stripname_cnf ()
 {
-  case ${2} in
-  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
-  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
+  case @S|@2 in
+  .*) func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%\\\\@S|@2\$%%"`;;
+  *)  func_stripname_result=`$ECHO "@S|@3" | $SED "s%^@S|@1%%; s%@S|@2\$%%"`;;
   esac
 } # func_stripname_cnf
 ])# _LT_FUNC_STRIPNAME_CNF
 
+
 # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
 # ---------------------------------
 # Figure out "hidden" library dependencies from verbose
@@ -7007,13 +7547,13 @@ if AC_TRY_EVAL(ac_compile); then
   pre_test_object_deps_done=no
 
   for p in `eval "$output_verbose_link_cmd"`; do
-    case ${prev}${p} in
+    case $prev$p in
 
     -L* | -R* | -l*)
        # Some compilers place space between "-{L,R}" and the path.
        # Remove the space.
-       if test $p = "-L" ||
-          test $p = "-R"; then
+       if test x-L = "$p" ||
+          test x-R = "$p"; then
 	 prev=$p
 	 continue
        fi
@@ -7029,16 +7569,16 @@ if AC_TRY_EVAL(ac_compile); then
        case $p in
        =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
        esac
-       if test "$pre_test_object_deps_done" = no; then
-	 case ${prev} in
+       if test no = "$pre_test_object_deps_done"; then
+	 case $prev in
 	 -L | -R)
 	   # Internal compiler library paths should come after those
 	   # provided the user.  The postdeps already come after the
 	   # user supplied libs so there is no need to process them.
 	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+	     _LT_TAGVAR(compiler_lib_search_path, $1)=$prev$p
 	   else
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} $prev$p"
 	   fi
 	   ;;
 	 # The "-l" case would never come before the object being
@@ -7046,9 +7586,9 @@ if AC_TRY_EVAL(ac_compile); then
 	 esac
        else
 	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
-	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+	   _LT_TAGVAR(postdeps, $1)=$prev$p
 	 else
-	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} $prev$p"
 	 fi
        fi
        prev=
@@ -7063,15 +7603,15 @@ if AC_TRY_EVAL(ac_compile); then
 	 continue
        fi
 
-       if test "$pre_test_object_deps_done" = no; then
+       if test no = "$pre_test_object_deps_done"; then
 	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
-	   _LT_TAGVAR(predep_objects, $1)="$p"
+	   _LT_TAGVAR(predep_objects, $1)=$p
 	 else
 	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
 	 fi
        else
 	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
-	   _LT_TAGVAR(postdep_objects, $1)="$p"
+	   _LT_TAGVAR(postdep_objects, $1)=$p
 	 else
 	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
 	 fi
@@ -7102,51 +7642,6 @@ interix[[3-9]]*)
   _LT_TAGVAR(postdep_objects,$1)=
   _LT_TAGVAR(postdeps,$1)=
   ;;
-
-linux*)
-  case `$CC -V 2>&1 | sed 5q` in
-  *Sun\ C*)
-    # Sun C++ 5.9
-
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC* | sunCC*)
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
 esac
 ])
 
@@ -7155,7 +7650,7 @@ case " $_LT_TAGVAR(postdeps, $1) " in
 esac
  _LT_TAGVAR(compiler_lib_search_dirs, $1)=
 if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | $SED -e 's! -L! !g' -e 's!^ !!'`
 fi
 _LT_TAGDECL([], [compiler_lib_search_dirs], [1],
     [The directories searched by this compiler when creating a shared library])
@@ -7175,10 +7670,10 @@ _LT_TAGDECL([], [compiler_lib_search_path], [1],
 # --------------------------
 # Ensure that the configuration variables for a Fortran 77 compiler are
 # suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
+# to write the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_F77_CONFIG],
 [AC_LANG_PUSH(Fortran 77)
-if test -z "$F77" || test "X$F77" = "Xno"; then
+if test -z "$F77" || test no = "$F77"; then
   _lt_disable_F77=yes
 fi
 
@@ -7215,7 +7710,7 @@ _LT_TAGVAR(objext, $1)=$objext
 # the F77 compiler isn't working.  Some variables (like enable_shared)
 # are currently assumed to apply to all compilers on this platform,
 # and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_F77" != yes; then
+if test yes != "$_lt_disable_F77"; then
   # Code to be used in simple compile tests
   lt_simple_compile_test_code="\
       subroutine t
@@ -7237,7 +7732,7 @@ if test "$_lt_disable_F77" != yes; then
   _LT_LINKER_BOILERPLATE
 
   # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
+  lt_save_CC=$CC
   lt_save_GCC=$GCC
   lt_save_CFLAGS=$CFLAGS
   CC=${F77-"f77"}
@@ -7251,21 +7746,25 @@ if test "$_lt_disable_F77" != yes; then
     AC_MSG_RESULT([$can_build_shared])
 
     AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
+    test no = "$can_build_shared" && enable_shared=no
 
     # On AIX, shared libraries and static libraries use the same namespace, and
     # are all built from PIC.
     case $host_os in
       aix3*)
-        test "$enable_shared" = yes && enable_static=no
+        test yes = "$enable_shared" && enable_static=no
         if test -n "$RANLIB"; then
           archive_cmds="$archive_cmds~\$RANLIB \$lib"
           postinstall_cmds='$RANLIB $lib'
         fi
         ;;
       aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
+	if test ia64 != "$host_cpu"; then
+	  case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in
+	  yes,aix,yes) ;;		# shared object as lib.so file only
+	  yes,svr4,*) ;;		# shared object as lib.so archive member only
+	  yes,*) enable_static=no ;;	# shared object in lib.a archive as well
+	  esac
 	fi
         ;;
     esac
@@ -7273,11 +7772,11 @@ if test "$_lt_disable_F77" != yes; then
 
     AC_MSG_CHECKING([whether to build static libraries])
     # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
+    test yes = "$enable_shared" || enable_static=yes
     AC_MSG_RESULT([$enable_static])
 
-    _LT_TAGVAR(GCC, $1)="$G77"
-    _LT_TAGVAR(LD, $1)="$LD"
+    _LT_TAGVAR(GCC, $1)=$G77
+    _LT_TAGVAR(LD, $1)=$LD
 
     ## CAVEAT EMPTOR:
     ## There is no encapsulation within the following macros, do not change
@@ -7294,9 +7793,9 @@ if test "$_lt_disable_F77" != yes; then
   fi # test -n "$compiler"
 
   GCC=$lt_save_GCC
-  CC="$lt_save_CC"
-  CFLAGS="$lt_save_CFLAGS"
-fi # test "$_lt_disable_F77" != yes
+  CC=$lt_save_CC
+  CFLAGS=$lt_save_CFLAGS
+fi # test yes != "$_lt_disable_F77"
 
 AC_LANG_POP
 ])# _LT_LANG_F77_CONFIG
@@ -7306,11 +7805,11 @@ AC_LANG_POP
 # -------------------------
 # Ensure that the configuration variables for a Fortran compiler are
 # suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
+# to write the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_FC_CONFIG],
 [AC_LANG_PUSH(Fortran)
 
-if test -z "$FC" || test "X$FC" = "Xno"; then
+if test -z "$FC" || test no = "$FC"; then
   _lt_disable_FC=yes
 fi
 
@@ -7347,7 +7846,7 @@ _LT_TAGVAR(objext, $1)=$objext
 # the FC compiler isn't working.  Some variables (like enable_shared)
 # are currently assumed to apply to all compilers on this platform,
 # and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_FC" != yes; then
+if test yes != "$_lt_disable_FC"; then
   # Code to be used in simple compile tests
   lt_simple_compile_test_code="\
       subroutine t
@@ -7369,7 +7868,7 @@ if test "$_lt_disable_FC" != yes; then
   _LT_LINKER_BOILERPLATE
 
   # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
+  lt_save_CC=$CC
   lt_save_GCC=$GCC
   lt_save_CFLAGS=$CFLAGS
   CC=${FC-"f95"}
@@ -7385,21 +7884,25 @@ if test "$_lt_disable_FC" != yes; then
     AC_MSG_RESULT([$can_build_shared])
 
     AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
+    test no = "$can_build_shared" && enable_shared=no
 
     # On AIX, shared libraries and static libraries use the same namespace, and
     # are all built from PIC.
     case $host_os in
       aix3*)
-        test "$enable_shared" = yes && enable_static=no
+        test yes = "$enable_shared" && enable_static=no
         if test -n "$RANLIB"; then
           archive_cmds="$archive_cmds~\$RANLIB \$lib"
           postinstall_cmds='$RANLIB $lib'
         fi
         ;;
       aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
+	if test ia64 != "$host_cpu"; then
+	  case $enable_shared,$with_aix_soname,$aix_use_runtimelinking in
+	  yes,aix,yes) ;;		# shared object as lib.so file only
+	  yes,svr4,*) ;;		# shared object as lib.so archive member only
+	  yes,*) enable_static=no ;;	# shared object in lib.a archive as well
+	  esac
 	fi
         ;;
     esac
@@ -7407,11 +7910,11 @@ if test "$_lt_disable_FC" != yes; then
 
     AC_MSG_CHECKING([whether to build static libraries])
     # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
+    test yes = "$enable_shared" || enable_static=yes
     AC_MSG_RESULT([$enable_static])
 
-    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
-    _LT_TAGVAR(LD, $1)="$LD"
+    _LT_TAGVAR(GCC, $1)=$ac_cv_fc_compiler_gnu
+    _LT_TAGVAR(LD, $1)=$LD
 
     ## CAVEAT EMPTOR:
     ## There is no encapsulation within the following macros, do not change
@@ -7431,7 +7934,7 @@ if test "$_lt_disable_FC" != yes; then
   GCC=$lt_save_GCC
   CC=$lt_save_CC
   CFLAGS=$lt_save_CFLAGS
-fi # test "$_lt_disable_FC" != yes
+fi # test yes != "$_lt_disable_FC"
 
 AC_LANG_POP
 ])# _LT_LANG_FC_CONFIG
@@ -7441,7 +7944,7 @@ AC_LANG_POP
 # --------------------------
 # Ensure that the configuration variables for the GNU Java Compiler compiler
 # are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
+# to write the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_GCJ_CONFIG],
 [AC_REQUIRE([LT_PROG_GCJ])dnl
 AC_LANG_SAVE
@@ -7475,7 +7978,7 @@ CC=${GCJ-"gcj"}
 CFLAGS=$GCJFLAGS
 compiler=$CC
 _LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
+_LT_TAGVAR(LD, $1)=$LD
 _LT_CC_BASENAME([$compiler])
 
 # GCJ did not exist at the time GCC didn't implicitly link libc in.
@@ -7512,7 +8015,7 @@ CFLAGS=$lt_save_CFLAGS
 # --------------------------
 # Ensure that the configuration variables for the GNU Go compiler
 # are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
+# to write the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_GO_CONFIG],
 [AC_REQUIRE([LT_PROG_GO])dnl
 AC_LANG_SAVE
@@ -7546,7 +8049,7 @@ CC=${GOC-"gccgo"}
 CFLAGS=$GOFLAGS
 compiler=$CC
 _LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
+_LT_TAGVAR(LD, $1)=$LD
 _LT_CC_BASENAME([$compiler])
 
 # Go did not exist at the time GCC didn't implicitly link libc in.
@@ -7583,7 +8086,7 @@ CFLAGS=$lt_save_CFLAGS
 # -------------------------
 # Ensure that the configuration variables for the Windows resource compiler
 # are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
+# to write the compiler configuration to 'libtool'.
 m4_defun([_LT_LANG_RC_CONFIG],
 [AC_REQUIRE([LT_PROG_RC])dnl
 AC_LANG_SAVE
@@ -7599,7 +8102,7 @@ _LT_TAGVAR(objext, $1)=$objext
 lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
 
 # Code to be used in simple link tests
-lt_simple_link_test_code="$lt_simple_compile_test_code"
+lt_simple_link_test_code=$lt_simple_compile_test_code
 
 # ltmain only uses $CC for tagged configurations so make sure $CC is set.
 _LT_TAG_COMPILER
@@ -7609,7 +8112,7 @@ _LT_COMPILER_BOILERPLATE
 _LT_LINKER_BOILERPLATE
 
 # Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
+lt_save_CC=$CC
 lt_save_CFLAGS=$CFLAGS
 lt_save_GCC=$GCC
 GCC=
@@ -7638,7 +8141,7 @@ AC_DEFUN([LT_PROG_GCJ],
 [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
   [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
     [AC_CHECK_TOOL(GCJ, gcj,)
-      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      test set = "${GCJFLAGS+set}" || GCJFLAGS="-g -O2"
       AC_SUBST(GCJFLAGS)])])[]dnl
 ])
 
@@ -7749,7 +8252,7 @@ lt_ac_count=0
 # Add /usr/xpg4/bin/sed as it is typically found on Solaris
 # along with /bin/sed that truncates output.
 for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
+  test ! -f "$lt_ac_sed" && continue
   cat /dev/null > conftest.in
   lt_ac_count=0
   echo $ECHO_N "0123456789$ECHO_C" >conftest.in
@@ -7766,9 +8269,9 @@ for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
     $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
     cmp -s conftest.out conftest.nl || break
     # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
+    test 10 -lt "$lt_ac_count" && break
     lt_ac_count=`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
+    if test "$lt_ac_count" -gt "$lt_ac_max"; then
       lt_ac_max=$lt_ac_count
       lt_cv_path_SED=$lt_ac_sed
     fi
@@ -7792,27 +8295,7 @@ dnl AC_DEFUN([LT_AC_PROG_SED], [])
 # Find out whether the shell is Bourne or XSI compatible,
 # or has some other useful features.
 m4_defun([_LT_CHECK_SHELL_FEATURES],
-[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-AC_MSG_RESULT([$xsi_shell])
-_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
-
-AC_MSG_CHECKING([whether the shell understands "+="])
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-AC_MSG_RESULT([$lt_shell_append])
-_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
-
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+[if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
   lt_unset=unset
 else
   lt_unset=false
@@ -7836,102 +8319,9 @@ _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
 ])# _LT_CHECK_SHELL_FEATURES
 
 
-# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
-# ------------------------------------------------------
-# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
-# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
-m4_defun([_LT_PROG_FUNCTION_REPLACE],
-[dnl {
-sed -e '/^$1 ()$/,/^} # $1 /c\
-$1 ()\
-{\
-m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
-} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-])
-
-
-# _LT_PROG_REPLACE_SHELLFNS
-# -------------------------
-# Replace existing portable implementations of several shell functions with
-# equivalent extended shell implementations where those features are available..
-m4_defun([_LT_PROG_REPLACE_SHELLFNS],
-[if test x"$xsi_shell" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
-    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
-    # positional parameters, so assign one to ordinary parameter first.
-    func_stripname_result=${3}
-    func_stripname_result=${func_stripname_result#"${1}"}
-    func_stripname_result=${func_stripname_result%"${2}"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
-    func_split_long_opt_name=${1%%=*}
-    func_split_long_opt_arg=${1#*=}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
-    func_split_short_opt_arg=${1#??}
-    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
-    case ${1} in
-      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
-      *)    func_lo2o_result=${1} ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
-
-  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
-
-  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
-fi
-
-if test x"$lt_shell_append" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
-    func_quote_for_eval "${2}"
-dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
-    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
-
-  # Save a `func_append' function call where possible by direct use of '+='
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-else
-  # Save a `func_append' function call even when '+=' is not available
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-fi
-
-if test x"$_lt_function_replace_fail" = x":"; then
-  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
-fi
-])
-
 # _LT_PATH_CONVERSION_FUNCTIONS
 # -----------------------------
-# Determine which file name conversion functions should be used by
+# Determine what file name conversion functions should be used by
 # func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
 # for certain cross-compile configurations and native mingw.
 m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
diff --git a/autostuff/ltoptions.m4 b/m4/ltoptions.m4
similarity index 73%
rename from autostuff/ltoptions.m4
rename to m4/ltoptions.m4
index 5d9acd8..94b0829 100644
--- a/autostuff/ltoptions.m4
+++ b/m4/ltoptions.m4
@@ -1,14 +1,14 @@
 # Helper functions for option handling.                    -*- Autoconf -*-
 #
-#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
-#   Inc.
+#   Copyright (C) 2004-2005, 2007-2009, 2011-2015 Free Software
+#   Foundation, Inc.
 #   Written by Gary V. Vaughan, 2004
 #
 # This file is free software; the Free Software Foundation gives
 # unlimited permission to copy and/or distribute it, with or without
 # modifications, as long as this notice is preserved.
 
-# serial 7 ltoptions.m4
+# serial 8 ltoptions.m4
 
 # This is to help aclocal find these macros, as it can't see m4_define.
 AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
@@ -29,7 +29,7 @@ m4_define([_LT_SET_OPTION],
 [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
 m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
         _LT_MANGLE_DEFUN([$1], [$2]),
-    [m4_warning([Unknown $1 option `$2'])])[]dnl
+    [m4_warning([Unknown $1 option '$2'])])[]dnl
 ])
 
 
@@ -75,13 +75,15 @@ m4_if([$1],[LT_INIT],[
   dnl
   dnl If no reference was made to various pairs of opposing options, then
   dnl we run the default mode handler for the pair.  For example, if neither
-  dnl `shared' nor `disable-shared' was passed, we enable building of shared
+  dnl 'shared' nor 'disable-shared' was passed, we enable building of shared
   dnl archives by default:
   _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
   _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
   _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
   _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
-  		   [_LT_ENABLE_FAST_INSTALL])
+		   [_LT_ENABLE_FAST_INSTALL])
+  _LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4],
+		   [_LT_WITH_AIX_SONAME([aix])])
   ])
 ])# _LT_SET_OPTIONS
 
@@ -112,7 +114,7 @@ AU_DEFUN([AC_LIBTOOL_DLOPEN],
 [_LT_SET_OPTION([LT_INIT], [dlopen])
 AC_DIAGNOSE([obsolete],
 [$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `dlopen' option into LT_INIT's first parameter.])
+put the 'dlopen' option into LT_INIT's first parameter.])
 ])
 
 dnl aclocal-1.4 backwards compatibility:
@@ -148,7 +150,7 @@ AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
 _LT_SET_OPTION([LT_INIT], [win32-dll])
 AC_DIAGNOSE([obsolete],
 [$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `win32-dll' option into LT_INIT's first parameter.])
+put the 'win32-dll' option into LT_INIT's first parameter.])
 ])
 
 dnl aclocal-1.4 backwards compatibility:
@@ -157,9 +159,9 @@ dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
 
 # _LT_ENABLE_SHARED([DEFAULT])
 # ----------------------------
-# implement the --enable-shared flag, and supports the `shared' and
-# `disable-shared' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+# implement the --enable-shared flag, and supports the 'shared' and
+# 'disable-shared' LT_INIT options.
+# DEFAULT is either 'yes' or 'no'.  If omitted, it defaults to 'yes'.
 m4_define([_LT_ENABLE_SHARED],
 [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
 AC_ARG_ENABLE([shared],
@@ -172,14 +174,14 @@ AC_ARG_ENABLE([shared],
     *)
       enable_shared=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_shared=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac],
     [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
@@ -211,9 +213,9 @@ dnl AC_DEFUN([AM_DISABLE_SHARED], [])
 
 # _LT_ENABLE_STATIC([DEFAULT])
 # ----------------------------
-# implement the --enable-static flag, and support the `static' and
-# `disable-static' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+# implement the --enable-static flag, and support the 'static' and
+# 'disable-static' LT_INIT options.
+# DEFAULT is either 'yes' or 'no'.  If omitted, it defaults to 'yes'.
 m4_define([_LT_ENABLE_STATIC],
 [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
 AC_ARG_ENABLE([static],
@@ -226,14 +228,14 @@ AC_ARG_ENABLE([static],
     *)
      enable_static=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_static=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac],
     [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
@@ -265,9 +267,9 @@ dnl AC_DEFUN([AM_DISABLE_STATIC], [])
 
 # _LT_ENABLE_FAST_INSTALL([DEFAULT])
 # ----------------------------------
-# implement the --enable-fast-install flag, and support the `fast-install'
-# and `disable-fast-install' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
+# implement the --enable-fast-install flag, and support the 'fast-install'
+# and 'disable-fast-install' LT_INIT options.
+# DEFAULT is either 'yes' or 'no'.  If omitted, it defaults to 'yes'.
 m4_define([_LT_ENABLE_FAST_INSTALL],
 [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
 AC_ARG_ENABLE([fast-install],
@@ -280,14 +282,14 @@ AC_ARG_ENABLE([fast-install],
     *)
       enable_fast_install=no
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for pkg in $enableval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$pkg" = "X$p"; then
 	  enable_fast_install=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac],
     [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
@@ -304,14 +306,14 @@ AU_DEFUN([AC_ENABLE_FAST_INSTALL],
 [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
 AC_DIAGNOSE([obsolete],
 [$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `fast-install' option into LT_INIT's first parameter.])
+the 'fast-install' option into LT_INIT's first parameter.])
 ])
 
 AU_DEFUN([AC_DISABLE_FAST_INSTALL],
 [_LT_SET_OPTION([LT_INIT], [disable-fast-install])
 AC_DIAGNOSE([obsolete],
 [$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `disable-fast-install' option into LT_INIT's first parameter.])
+the 'disable-fast-install' option into LT_INIT's first parameter.])
 ])
 
 dnl aclocal-1.4 backwards compatibility:
@@ -319,11 +321,64 @@ dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
 dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
 
 
+# _LT_WITH_AIX_SONAME([DEFAULT])
+# ----------------------------------
+# implement the --with-aix-soname flag, and support the `aix-soname=aix'
+# and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT
+# is either `aix', `both' or `svr4'.  If omitted, it defaults to `aix'.
+m4_define([_LT_WITH_AIX_SONAME],
+[m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl
+shared_archive_member_spec=
+case $host,$enable_shared in
+power*-*-aix[[5-9]]*,yes)
+  AC_MSG_CHECKING([which variant of shared library versioning to provide])
+  AC_ARG_WITH([aix-soname],
+    [AS_HELP_STRING([--with-aix-soname=aix|svr4|both],
+      [shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])],
+    [case $withval in
+    aix|svr4|both)
+      ;;
+    *)
+      AC_MSG_ERROR([Unknown argument to --with-aix-soname])
+      ;;
+    esac
+    lt_cv_with_aix_soname=$with_aix_soname],
+    [AC_CACHE_VAL([lt_cv_with_aix_soname],
+      [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT)
+    with_aix_soname=$lt_cv_with_aix_soname])
+  AC_MSG_RESULT([$with_aix_soname])
+  if test aix != "$with_aix_soname"; then
+    # For the AIX way of multilib, we name the shared archive member
+    # based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o',
+    # and 'shr.imp' or 'shr_64.imp', respectively, for the Import File.
+    # Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag,
+    # the AIX toolchain works better with OBJECT_MODE set (default 32).
+    if test 64 = "${OBJECT_MODE-32}"; then
+      shared_archive_member_spec=shr_64
+    else
+      shared_archive_member_spec=shr
+    fi
+  fi
+  ;;
+*)
+  with_aix_soname=aix
+  ;;
+esac
+
+_LT_DECL([], [shared_archive_member_spec], [0],
+    [Shared archive member basename, for filename based shared library versioning on AIX])dnl
+])# _LT_WITH_AIX_SONAME
+
+LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])])
+LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])])
+LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])])
+
+
 # _LT_WITH_PIC([MODE])
 # --------------------
-# implement the --with-pic flag, and support the `pic-only' and `no-pic'
+# implement the --with-pic flag, and support the 'pic-only' and 'no-pic'
 # LT_INIT options.
-# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
+# MODE is either 'yes' or 'no'.  If omitted, it defaults to 'both'.
 m4_define([_LT_WITH_PIC],
 [AC_ARG_WITH([pic],
     [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
@@ -334,19 +389,17 @@ m4_define([_LT_WITH_PIC],
     *)
       pic_mode=default
       # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
+      lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
       for lt_pkg in $withval; do
-	IFS="$lt_save_ifs"
+	IFS=$lt_save_ifs
 	if test "X$lt_pkg" = "X$lt_p"; then
 	  pic_mode=yes
 	fi
       done
-      IFS="$lt_save_ifs"
+      IFS=$lt_save_ifs
       ;;
     esac],
-    [pic_mode=default])
-
-test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
+    [pic_mode=m4_default([$1], [default])])
 
 _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
 ])# _LT_WITH_PIC
@@ -359,7 +412,7 @@ AU_DEFUN([AC_LIBTOOL_PICMODE],
 [_LT_SET_OPTION([LT_INIT], [pic-only])
 AC_DIAGNOSE([obsolete],
 [$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `pic-only' option into LT_INIT's first parameter.])
+put the 'pic-only' option into LT_INIT's first parameter.])
 ])
 
 dnl aclocal-1.4 backwards compatibility:
diff --git a/autostuff/ltsugar.m4 b/m4/ltsugar.m4
similarity index 95%
rename from autostuff/ltsugar.m4
rename to m4/ltsugar.m4
index 9000a05..48bc934 100644
--- a/autostuff/ltsugar.m4
+++ b/m4/ltsugar.m4
@@ -1,6 +1,7 @@
 # ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
 #
-# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
+# Copyright (C) 2004-2005, 2007-2008, 2011-2015 Free Software
+# Foundation, Inc.
 # Written by Gary V. Vaughan, 2004
 #
 # This file is free software; the Free Software Foundation gives
@@ -33,7 +34,7 @@ m4_define([_lt_join],
 # ------------
 # Manipulate m4 lists.
 # These macros are necessary as long as will still need to support
-# Autoconf-2.59 which quotes differently.
+# Autoconf-2.59, which quotes differently.
 m4_define([lt_car], [[$1]])
 m4_define([lt_cdr],
 [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
@@ -44,7 +45,7 @@ m4_define([lt_unquote], $1)
 
 # lt_append(MACRO-NAME, STRING, [SEPARATOR])
 # ------------------------------------------
-# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
+# Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'.
 # Note that neither SEPARATOR nor STRING are expanded; they are appended
 # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
 # No SEPARATOR is output if MACRO-NAME was previously undefined (different
diff --git a/autostuff/ltversion.m4 b/m4/ltversion.m4
similarity index 68%
rename from autostuff/ltversion.m4
rename to m4/ltversion.m4
index 07a8602..fa04b52 100644
--- a/autostuff/ltversion.m4
+++ b/m4/ltversion.m4
@@ -1,6 +1,6 @@
 # ltversion.m4 -- version numbers			-*- Autoconf -*-
 #
-#   Copyright (C) 2004 Free Software Foundation, Inc.
+#   Copyright (C) 2004, 2011-2015 Free Software Foundation, Inc.
 #   Written by Scott James Remnant, 2004
 #
 # This file is free software; the Free Software Foundation gives
@@ -9,15 +9,15 @@
 
 # @configure_input@
 
-# serial 3337 ltversion.m4
+# serial 4179 ltversion.m4
 # This file is part of GNU Libtool
 
-m4_define([LT_PACKAGE_VERSION], [2.4.2])
-m4_define([LT_PACKAGE_REVISION], [1.3337])
+m4_define([LT_PACKAGE_VERSION], [2.4.6])
+m4_define([LT_PACKAGE_REVISION], [2.4.6])
 
 AC_DEFUN([LTVERSION_VERSION],
-[macro_version='2.4.2'
-macro_revision='1.3337'
+[macro_version='2.4.6'
+macro_revision='2.4.6'
 _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
 _LT_DECL(, macro_revision, 0)
 ])
diff --git a/autostuff/lt~obsolete.m4 b/m4/lt~obsolete.m4
similarity index 98%
rename from autostuff/lt~obsolete.m4
rename to m4/lt~obsolete.m4
index c573da9..c6b26f8 100644
--- a/autostuff/lt~obsolete.m4
+++ b/m4/lt~obsolete.m4
@@ -1,6 +1,7 @@
 # lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
 #
-#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
+#   Copyright (C) 2004-2005, 2007, 2009, 2011-2015 Free Software
+#   Foundation, Inc.
 #   Written by Scott James Remnant, 2004.
 #
 # This file is free software; the Free Software Foundation gives
@@ -11,7 +12,7 @@
 
 # These exist entirely to fool aclocal when bootstrapping libtool.
 #
-# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
+# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN),
 # which have later been changed to m4_define as they aren't part of the
 # exported API, or moved to Autoconf or Automake where they belong.
 #
@@ -25,7 +26,7 @@
 # included after everything else.  This provides aclocal with the
 # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
 # because those macros already exist, or will be overwritten later.
-# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
+# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6.
 #
 # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
 # Yes, that means every name once taken will need to remain here until
diff --git a/m4/sigrok.m4 b/m4/sigrok.m4
new file mode 100644
index 0000000..2ca2444
--- /dev/null
+++ b/m4/sigrok.m4
@@ -0,0 +1,449 @@
+##
+## This file is part of the sigrok project.
+##
+## Copyright (C) 2009 Openismus GmbH
+## Copyright (C) 2015 Daniel Elstner <daniel.kitta at gmail.com>
+##
+## 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 3 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, see <http://www.gnu.org/licenses/>.
+##
+
+#serial 20150910
+
+## SR_APPEND(var-name, [list-sep,] element)
+##
+## Append the shell word <element> to the shell variable named <var-name>,
+## prefixed by <list-sep> unless the list was empty before appending. If
+## only two arguments are supplied, <list-sep> defaults to a single space
+## character.
+##
+AC_DEFUN([SR_APPEND],
+[dnl
+m4_assert([$# >= 2])[]dnl
+$1=[$]{$1[}]m4_if([$#], [2], [[$]{$1:+' '}$2], [[$]{$1:+$2}$3])[]dnl
+])
+
+## SR_PREPEND(var-name, [list-sep,] element)
+##
+## Prepend the shell word <element> to the shell variable named <var-name>,
+## suffixed by <list-sep> unless the list was empty before prepending. If
+## only two arguments are supplied, <list-sep> defaults to a single space
+## character.
+##
+AC_DEFUN([SR_PREPEND],
+[dnl
+m4_assert([$# >= 2])[]dnl
+$1=m4_if([$#], [2], [$2[$]{$1:+' '}], [$3[$]{$1:+$2}])[$]$1[]dnl
+])
+
+## _SR_PKG_VERSION_SET(var-prefix, pkg-name, tag-prefix, base-version, major, minor, [micro])
+##
+m4_define([_SR_PKG_VERSION_SET],
+[dnl
+m4_assert([$# >= 6])[]dnl
+$1=$4
+sr_git_deps=
+# Check if we can get revision information from git.
+sr_head=`git -C "$srcdir" rev-parse --verify --short HEAD 2>&AS_MESSAGE_LOG_FD`
+
+AS_IF([test "$?" = 0 && test "x$sr_head" != x], [dnl
+	test ! -f "$srcdir/.git/HEAD" \
+		|| sr_git_deps="$sr_git_deps \$(top_srcdir)/.git/HEAD"
+
+	sr_head_name=`git -C "$srcdir" rev-parse --symbolic-full-name HEAD 2>&AS_MESSAGE_LOG_FD`
+	AS_IF([test "$?" = 0 && test -f "$srcdir/.git/$sr_head_name"],
+		[sr_git_deps="$sr_git_deps \$(top_srcdir)/.git/$sr_head_name"])
+
+	# Append the revision hash unless we are exactly on a tagged release.
+	git -C "$srcdir" describe --match "$3$4" \
+		--exact-match >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD \
+		|| $1="[$]$1-git-$sr_head"
+])
+# Use $(wildcard) so that things do not break if for whatever
+# reason these files do not exist anymore at make time.
+AS_IF([test -n "$sr_git_deps"],
+	[SR_APPEND([CONFIG_STATUS_DEPENDENCIES], ["\$(wildcard$sr_git_deps)"])])
+AC_SUBST([CONFIG_STATUS_DEPENDENCIES])[]dnl
+AC_SUBST([$1])[]dnl
+dnl
+AC_DEFINE([$1_MAJOR], [$5], [Major version number of $2.])[]dnl
+AC_DEFINE([$1_MINOR], [$6], [Minor version number of $2.])[]dnl
+m4_ifval([$7], [AC_DEFINE([$1_MICRO], [$7], [Micro version number of $2.])])[]dnl
+AC_DEFINE_UNQUOTED([$1_STRING], ["[$]$1"], [Version of $2.])[]dnl
+])
+
+## SR_PKG_VERSION_SET(var-prefix, version-triple)
+##
+## Set up substitution variables and macro definitions for the package
+## version components. Derive the version suffix from the repository
+## revision if possible.
+##
+## Substitutions: <var-prefix>
+## Macro defines: <var-prefix>_{MAJOR,MINOR,MICRO,STRING}
+##
+AC_DEFUN([SR_PKG_VERSION_SET],
+[dnl
+m4_assert([$# >= 2])[]dnl
+_SR_PKG_VERSION_SET([$1],
+	m4_defn([AC_PACKAGE_NAME]),
+	m4_defn([AC_PACKAGE_TARNAME])[-],
+	m4_expand([$2]),
+	m4_unquote(m4_split(m4_expand([$2]), [\.])))
+])
+
+## _SR_LIB_VERSION_SET(var-prefix, pkg-name, abi-triple, current, revision, age)
+##
+m4_define([_SR_LIB_VERSION_SET],
+[dnl
+m4_assert([$# >= 6])[]dnl
+$1=$3
+AC_SUBST([$1])[]dnl
+AC_DEFINE([$1_CURRENT], [$4], [Binary version of $2.])[]dnl
+AC_DEFINE([$1_REVISION], [$5], [Binary revision of $2.])[]dnl
+AC_DEFINE([$1_AGE], [$6], [Binary age of $2.])[]dnl
+AC_DEFINE([$1_STRING], ["$3"], [Binary version triple of $2.])[]dnl
+])
+
+## SR_LIB_VERSION_SET(var-prefix, abi-triple)
+##
+## Set up substitution variables and macro definitions for a library
+## binary version.
+##
+## Substitutions: <var-prefix>
+## Macro defines: <var-prefix>_{CURRENT,REVISION,AGE,STRING}
+##
+AC_DEFUN([SR_LIB_VERSION_SET],
+[dnl
+m4_assert([$# >= 1])[]dnl
+_SR_LIB_VERSION_SET([$1],
+	m4_defn([AC_PACKAGE_NAME]),
+	[$2], m4_unquote(m4_split([$2], [:])))
+])
+
+## SR_SEARCH_LIBS(libs-var, function, search-libs,
+##                [action-if-found], [action-if-not-found], [other-libs])
+##
+## Same as AC_SEARCH_LIBS, except that the result is prepended
+## to <libs-var> instead of LIBS. Calls AC_SUBST on <libs-var>.
+##
+AC_DEFUN([SR_SEARCH_LIBS],
+[dnl
+m4_assert([$# >= 3])[]dnl
+sr_sl_save_LIBS=$LIBS
+AC_SEARCH_LIBS([$2], [$3],,, m4_join([$6], [[$]$1]))
+LIBS=$sr_sl_save_LIBS
+AS_CASE([$ac_cv_search_$2], [no*],,
+	[SR_PREPEND([$1], [$ac_cv_search_$2])])
+m4_ifvaln([$4$5], [AS_IF([test "x$ac_cv_search_$2" = xno], [$5], [$4])])[]dnl
+AC_SUBST([$1])[]dnl
+])
+
+## _SR_VAR_SUMMARY(tag, var-name, line-leader, align-columns, align-char)
+##
+m4_define([_SR_VAR_SUMMARY], [dnl
+$2=
+$1_append() {
+	sr_aligned=`printf '%.$4s' "[$][1]m4_for([i], [1], [$4],, [$5])"`
+	$2="[$]{$2}$3$sr_aligned [$]2"'
+'
+}
+])
+
+## SR_VAR_SUMMARY(tag, [var-name = <tag>],
+##                [line-leader = [ - ]], [align-columns = 32], [align-char = .])
+##
+## Define a shell function <tag>_append() to be used for aggregating
+## a summary of test results in the shell variable <var-name>.
+##
+AC_DEFUN([SR_VAR_SUMMARY],
+[dnl
+m4_assert([$# >= 1])[]dnl
+_SR_VAR_SUMMARY([$1],
+	m4_default_quoted([$2], [$1]),
+	m4_default_quoted([$3], [ - ]),
+	m4_default_quoted([$4], [32]),
+	m4_default_quoted([$5], [.]))[]dnl
+])
+
+## SR_PKG_CHECK_SUMMARY([var-name = sr_pkg_check_summary],
+##                      [line-leader = [ - ]], [align-columns = 32], [align-char = .])
+##
+## Prepare for the aggregation of package check results
+## in the shell variable <var-name>.
+##
+AC_DEFUN([SR_PKG_CHECK_SUMMARY],
+	[SR_VAR_SUMMARY([sr_pkg_check_summary], $@)])
+
+## SR_PKG_CHECK(tag, [collect-var], module...)
+##
+## Check for each pkg-config <module> in the argument list. <module> may
+## include a version constraint.
+##
+## Output variables: sr_have_<tag>, sr_<tag>_version
+##
+AC_DEFUN([SR_PKG_CHECK],
+[dnl
+m4_assert([$# >= 3])[]dnl
+AC_REQUIRE([PKG_PROG_PKG_CONFIG])[]dnl
+AC_REQUIRE([SR_PKG_CHECK_SUMMARY])[]dnl
+dnl
+PKG_CHECK_EXISTS([$3], [dnl
+	sr_have_$1=yes
+	m4_ifval([$2], [SR_APPEND([$2], ["$3"])
+	])sr_$1_version=`$PKG_CONFIG --modversion "$3" 2>&AS_MESSAGE_LOG_FD`
+	sr_pkg_check_summary_append "$3" "$sr_$1_version"[]dnl
+], [dnl
+	sr_pkg_check_summary_append "$3" no
+	m4_ifval([$4],
+		[SR_PKG_CHECK([$1], [$2], m4_shift3($@))],
+		[sr_have_$1=no sr_$1_version=])[]dnl
+])
+])
+
+## SR_VAR_OPT_PKG([modules-var], [features-var])
+##
+## Enable the collection of SR_ARG_OPT_PKG results into the shell variables
+## <modules-var> and <features-var>.
+##
+AC_DEFUN([SR_VAR_OPT_PKG],
+[dnl
+m4_define([_SR_VAR_OPT_PKG_MODULES], [$1])[]dnl
+m4_define([_SR_VAR_OPT_PKG_FEATURES], [$2])[]dnl
+m4_ifvaln([$1], [$1=])[]dnl
+m4_ifvaln([$2], [$2=])[]dnl
+])
+
+## _SR_ARG_OPT_IMPL(sh-name, [features-var], opt-name,
+##                  [cpp-name], [cond-name], check-commands)
+##
+m4_define([_SR_ARG_OPT_IMPL],
+[dnl
+AC_ARG_WITH([$3], [AS_HELP_STRING([--without-$3],
+			[disable $3 support [default=detect]])])
+AS_IF([test "x$with_$1" = xno], [sr_have_$1=no],
+	[test "x$sr_have_$1" != xyes], [dnl
+AC_MSG_CHECKING([for $3])
+$6
+AC_MSG_RESULT([$sr_have_$1])[]dnl
+])
+AS_IF([test "x$with_$1$sr_have_$1" = xyesno],
+	[AC_MSG_ERROR([$3 support requested, but it was not found.])])
+AS_IF([test "x$sr_have_$1" = xyes], [m4_ifval([$2], [
+	SR_APPEND([$2], ["$3"])])[]m4_ifval([$4], [
+	AC_DEFINE([HAVE_$4], [1], [Whether $3 is available.])])[]dnl
+])
+m4_ifvaln([$5], [AM_CONDITIONAL([$5], [test "x$sr_have_$1" = xyes])])[]dnl
+])
+
+## _SR_ARG_OPT_CHECK(sh-name, [features-var], opt-name, [cpp-name],
+##                   [cond-name], check-commands, [summary-result])
+##
+m4_define([_SR_ARG_OPT_CHECK],
+[dnl
+_SR_ARG_OPT_IMPL($@)
+sr_pkg_check_summary_append "$3" m4_default([$7], ["$sr_have_$1"])
+])
+
+## SR_ARG_OPT_CHECK(opt-name, [cpp-name], [cond-name], check-commands,
+##                  [summary-result = $sr_have_<opt-name>])
+##
+## Provide a --without-<opt-name> configure option for explicit disabling
+## of an optional dependency. If not disabled, the availability of the
+## optional dependency is auto-detected by running <check-commands>.
+##
+## The <check-commands> should set the shell variable sr_have_<opt-name>
+## to "yes" if the dependency is available, otherwise to "no". Optionally,
+## the <summary-result> argument may be used to generate a line in the
+## configuration summary. If supplied, it should be a shell word which
+## expands to the result to be displayed for the <opt-name> dependency.
+##
+## Use SR_VAR_OPT_PKG to generate lists of available modules and features.
+##
+AC_DEFUN([SR_ARG_OPT_CHECK],
+[dnl
+m4_assert([$# >= 4])[]dnl
+AC_REQUIRE([SR_PKG_CHECK_SUMMARY])[]dnl
+AC_REQUIRE([SR_VAR_OPT_PKG])[]dnl
+dnl
+_SR_ARG_OPT_CHECK(m4_expand([AS_TR_SH([$1])]),
+	m4_defn([_SR_VAR_OPT_PKG_FEATURES]),
+	$@)[]dnl
+])
+
+## _SR_ARG_OPT_PKG([features-var], [cond-name], opt-name,
+##                 [cpp-name], sh-name, [modules-var], module...)
+##
+m4_define([_SR_ARG_OPT_PKG],
+[dnl
+_SR_ARG_OPT_IMPL([$5], [$1], [$3], [$4], [$2],
+	[SR_PKG_CHECK(m4_shiftn([4], $@))])
+m4_ifvaln([$4], [AS_IF([test "x$sr_have_$5" = xyes],
+	[AC_DEFINE_UNQUOTED([CONF_$4_VERSION], ["$sr_$5_version"],
+		[Build-time version of $3.])])])[]dnl
+])
+
+## SR_ARG_OPT_PKG(opt-name, [cpp-name], [cond-name], module...)
+##
+## Provide a --without-<opt-name> configure option for explicit disabling
+## of an optional dependency. If not disabled, the availability of the
+## optional dependency is auto-detected.
+##
+## Each pkg-config <module> argument is checked in turn, and the first one
+## found is selected. On success, the shell variable sr_have_<opt-name>
+## is set to "yes", otherwise to "no". Optionally, a preprocessor macro
+## HAVE_<cpp-name> and an Automake conditional <cond-name> are generated.
+##
+## Use SR_VAR_OPT_PKG to generate lists of available modules and features.
+##
+AC_DEFUN([SR_ARG_OPT_PKG],
+[dnl
+m4_assert([$# >= 4])[]dnl
+AC_REQUIRE([PKG_PROG_PKG_CONFIG])[]dnl
+AC_REQUIRE([SR_PKG_CHECK_SUMMARY])[]dnl
+AC_REQUIRE([SR_VAR_OPT_PKG])[]dnl
+dnl
+_SR_ARG_OPT_PKG(m4_defn([_SR_VAR_OPT_PKG_FEATURES]),
+	[$3], [$1], [$2],
+	m4_expand([AS_TR_SH([$1])]),
+	m4_defn([_SR_VAR_OPT_PKG_MODULES]),
+	m4_shift3($@))[]dnl
+])
+
+## SR_PROG_VERSION(program, sh-var)
+##
+## Obtain the version of <program> and store it in <sh-var>.
+##
+AC_DEFUN([SR_PROG_VERSION],
+[dnl
+m4_assert([$# >= 2])[]dnl
+sr_prog_ver=`$1 --version 2>&AS_MESSAGE_LOG_FD | sed 1q 2>&AS_MESSAGE_LOG_FD`
+AS_CASE([[$]?:$sr_prog_ver],
+	[[0:*[0-9].[0-9]*]], [$2=$sr_prog_ver],
+	[$2=unknown])[]dnl
+])
+
+## SR_PROG_MAKE_ORDER_ONLY
+##
+## Check whether the make program supports order-only prerequisites.
+## If so, set the substitution variable ORDER to '|', or to the empty
+## string otherwise.
+##
+AC_DEFUN([SR_PROG_MAKE_ORDER_ONLY],
+[dnl
+AC_CACHE_CHECK([whether [$]{MAKE:-make} supports order-only prerequisites],
+	[sr_cv_prog_make_order_only], [
+cat >conftest.mk <<'_SREOF'
+a: b | c
+a b c: ; @:
+.PHONY: a b c
+_SREOF
+AS_IF([[$]{MAKE:-make} -f conftest.mk >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD],
+	[sr_cv_prog_make_order_only=yes], [sr_cv_prog_make_order_only=no])
+rm -f conftest.mk
+])
+AS_IF([test "x$sr_cv_prog_make_order_only" = xyes], [ORDER='|'], [ORDER=])
+AC_SUBST([ORDER])
+AM_SUBST_NOTMAKE([ORDER])[]dnl
+])
+
+## SR_CHECK_COMPILE_FLAGS(flags-var, description, flags)
+##
+## Find a compiler flag for <description>. For each flag in <flags>, check
+## if the compiler for the current language accepts it. On success, stop the
+## search and append the last tested flag to <flags-var>. Calls AC_SUBST
+## on <flags-var>.
+##
+AC_DEFUN([SR_CHECK_COMPILE_FLAGS],
+[dnl
+m4_assert([$# >= 3])[]dnl
+AC_MSG_CHECKING([compiler flag for $2])
+sr_ccf_result=no
+sr_ccf_save_CPPFLAGS=$CPPFLAGS
+for sr_flag in $3
+do
+	CPPFLAGS="$sr_ccf_save_CPPFLAGS $sr_flag"
+	AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [])], [sr_ccf_result=$sr_flag])
+	test "x$sr_ccf_result" = xno || break
+done
+CPPFLAGS=$sr_ccf_save_CPPFLAGS
+AS_IF([test "x$sr_ccf_result" != xno],
+	[SR_APPEND([$1], [$sr_ccf_result])])
+AC_MSG_RESULT([$sr_ccf_result])
+AC_SUBST([$1])
+])
+
+## _SR_ARG_ENABLE_WARNINGS_ONCE
+##
+## Implementation helper macro of SR_ARG_ENABLE_WARNINGS. Pulled in
+## through AC_REQUIRE so that it is only expanded once.
+##
+m4_define([_SR_ARG_ENABLE_WARNINGS_ONCE],
+[dnl
+AC_PROVIDE([$0])[]dnl
+AC_ARG_ENABLE([warnings],
+		[AS_HELP_STRING([[--enable-warnings[=min|max|fatal|no]]],
+				[set compile pedantry level [default=max]])],
+		[sr_enable_warnings=$enableval],
+		[sr_enable_warnings=max])[]dnl
+dnl
+# Test whether the compiler accepts each flag.  Look at standard output,
+# since GCC only shows a warning message if an option is not supported.
+sr_check_compile_warning_flags() {
+	for sr_flag
+	do
+		sr_cc_out=`$sr_cc $sr_warning_flags $sr_flag -c "$sr_conftest" 2>&1 || echo failed`
+		AS_IF([test "$?$sr_cc_out" = 0],
+			[SR_APPEND([sr_warning_flags], [$sr_flag])],
+			[AS_ECHO(["$sr_cc: $sr_cc_out"]) >&AS_MESSAGE_LOG_FD])
+		rm -f "conftest.[$]{OBJEXT:-o}"
+	done
+}
+])
+
+## SR_ARG_ENABLE_WARNINGS(variable, min-flags, max-flags)
+##
+## Provide the --enable-warnings configure argument, set to "min" by default.
+## <min-flags> and <max-flags> should be space-separated lists of compiler
+## warning flags to use with --enable-warnings=min or --enable-warnings=max,
+## respectively. Warning level "fatal" is the same as "max" but in addition
+## enables -Werror mode.
+##
+## In order to determine the warning options to use with the C++ compiler,
+## call AC_LANG([C++]) first to change the current language. If different
+## output variables are used, it is also fine to call SR_ARG_ENABLE_WARNINGS
+## repeatedly, once for each language setting.
+##
+AC_DEFUN([SR_ARG_ENABLE_WARNINGS],
+[dnl
+m4_assert([$# >= 3])[]dnl
+AC_REQUIRE([_SR_ARG_ENABLE_WARNINGS_ONCE])[]dnl
+dnl
+AS_CASE([$ac_compile],
+	[[*'$CXXFLAGS '*]], [sr_lang='C++' sr_cc=$CXX sr_conftest="conftest.[$]{ac_ext:-cc}"],
+	[[*'$CFLAGS '*]],   [sr_lang=C sr_cc=$CC sr_conftest="conftest.[$]{ac_ext:-c}"],
+	[AC_MSG_ERROR([[current language is neither C nor C++]])])
+dnl
+AC_MSG_CHECKING([which $sr_lang compiler warning flags to use])
+sr_warning_flags=
+AC_LANG_CONFTEST([AC_LANG_SOURCE([[
+int main(int argc, char** argv) { return (argv != 0) ? argc : 0; }
+]])])
+AS_CASE([$sr_enable_warnings],
+	[no], [],
+	[min], [sr_check_compile_warning_flags $2],
+	[fatal], [sr_check_compile_warning_flags $3 -Werror],
+	[sr_check_compile_warning_flags $3])
+rm -f "$sr_conftest"
+AC_SUBST([$1], [$sr_warning_flags])
+AC_MSG_RESULT([[$]{sr_warning_flags:-none}])[]dnl
+])
diff --git a/module_sigrokdecode.c b/module_sigrokdecode.c
index d5172d6..17563c1 100644
--- a/module_sigrokdecode.c
+++ b/module_sigrokdecode.c
@@ -17,17 +17,13 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 
 /** @cond PRIVATE */
 
-/* type_decoder.c */
-extern SRD_PRIV PyTypeObject srd_Decoder_type;
-
-/* type_logic.c */
-extern SRD_PRIV PyTypeObject srd_logic_type;
+SRD_PRIV PyObject *srd_logic_type = NULL;
 
 /*
  * When initialized, a reference to this module inside the Python interpreter
@@ -47,42 +43,45 @@ static struct PyModuleDef sigrokdecode_module = {
 /** @cond PRIVATE */
 PyMODINIT_FUNC PyInit_sigrokdecode(void)
 {
-	PyObject *mod;
+	PyObject *mod, *Decoder_type, *logic_type;
 
-	/* tp_new needs to be assigned here for compiler portability. */
-	srd_Decoder_type.tp_new = PyType_GenericNew;
-	if (PyType_Ready(&srd_Decoder_type) < 0)
-		return NULL;
+	mod = PyModule_Create(&sigrokdecode_module);
+	if (!mod)
+		goto err_out;
 
-	srd_logic_type.tp_new = PyType_GenericNew;
-	if (PyType_Ready(&srd_logic_type) < 0)
-		return NULL;
+	Decoder_type = srd_Decoder_type_new();
+	if (!Decoder_type)
+		goto err_out;
+	if (PyModule_AddObject(mod, "Decoder", Decoder_type) < 0)
+		goto err_out;
 
-	mod = PyModule_Create(&sigrokdecode_module);
-	Py_INCREF(&srd_Decoder_type);
-	if (PyModule_AddObject(mod, "Decoder",
-	    (PyObject *)&srd_Decoder_type) == -1)
-		return NULL;
-	Py_INCREF(&srd_logic_type);
-	if (PyModule_AddObject(mod, "srd_logic",
-	    (PyObject *)&srd_logic_type) == -1)
-		return NULL;
+	logic_type = srd_logic_type_new();
+	if (!logic_type)
+		goto err_out;
+	if (PyModule_AddObject(mod, "srd_logic", logic_type) < 0)
+		goto err_out;
 
 	/* Expose output types as symbols in the sigrokdecode module */
-	if (PyModule_AddIntConstant(mod, "OUTPUT_ANN", SRD_OUTPUT_ANN) == -1)
-		return NULL;
-	if (PyModule_AddIntConstant(mod, "OUTPUT_PYTHON", SRD_OUTPUT_PYTHON) == -1)
-		return NULL;
-	if (PyModule_AddIntConstant(mod, "OUTPUT_BINARY", SRD_OUTPUT_BINARY) == -1)
-		return NULL;
-	if (PyModule_AddIntConstant(mod, "OUTPUT_META", SRD_OUTPUT_META) == -1)
-		return NULL;
+	if (PyModule_AddIntConstant(mod, "OUTPUT_ANN", SRD_OUTPUT_ANN) < 0)
+		goto err_out;
+	if (PyModule_AddIntConstant(mod, "OUTPUT_PYTHON", SRD_OUTPUT_PYTHON) < 0)
+		goto err_out;
+	if (PyModule_AddIntConstant(mod, "OUTPUT_BINARY", SRD_OUTPUT_BINARY) < 0)
+		goto err_out;
+	if (PyModule_AddIntConstant(mod, "OUTPUT_META", SRD_OUTPUT_META) < 0)
+		goto err_out;
 	/* Expose meta input symbols. */
-	if (PyModule_AddIntConstant(mod, "SRD_CONF_SAMPLERATE", SRD_CONF_SAMPLERATE) == -1)
-		return NULL;
+	if (PyModule_AddIntConstant(mod, "SRD_CONF_SAMPLERATE", SRD_CONF_SAMPLERATE) < 0)
+		goto err_out;
 
+	srd_logic_type = logic_type;
 	mod_sigrokdecode = mod;
 
 	return mod;
+err_out:
+	Py_XDECREF(mod);
+	srd_exception_catch("Failed to initialize module");
+
+	return NULL;
 }
 /** @endcond */
diff --git a/session.c b/session.c
index 24846c5..e1bb4f9 100644
--- a/session.c
+++ b/session.c
@@ -18,9 +18,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <inttypes.h>
 #include <glib.h>
 
@@ -76,8 +76,7 @@ SRD_API int srd_session_new(struct srd_session **sess)
 		return SRD_ERR_ARG;
 	}
 
-	if (!(*sess = g_try_malloc(sizeof(struct srd_session))))
-		return SRD_ERR_MALLOC;
+	*sess = g_malloc(sizeof(struct srd_session));
 	(*sess)->session_id = ++max_session_id;
 	(*sess)->di_list = (*sess)->callbacks = NULL;
 
@@ -129,19 +128,27 @@ static int srd_inst_send_meta(struct srd_decoder_inst *di, int key,
 		GVariant *data)
 {
 	PyObject *py_ret;
+	GSList *l;
+	struct srd_decoder_inst *next_di;
+	int ret;
 
 	if (key != SRD_CONF_SAMPLERATE)
 		/* This is the only key we pass on to the decoder for now. */
 		return SRD_OK;
 
-	if (!PyObject_HasAttrString(di->py_inst, "metadata"))
-		/* This decoder doesn't want metadata, that's fine. */
-		return SRD_OK;
+	if (PyObject_HasAttrString(di->py_inst, "metadata")) {
+		py_ret = PyObject_CallMethod(di->py_inst, "metadata", "lK",
+				(long)SRD_CONF_SAMPLERATE,
+				(unsigned long long)g_variant_get_uint64(data));
+		Py_XDECREF(py_ret);
+	}
 
-	py_ret = PyObject_CallMethod(di->py_inst, "metadata", "lK",
-			(long)SRD_CONF_SAMPLERATE,
-			(unsigned long long)g_variant_get_uint64(data));
-	Py_XDECREF(py_ret);
+	/* Push metadata to all the PDs stacked on top of this one. */
+	for (l = di->next_di; l; l = l->next) {
+		next_di = l->data;
+		if ((ret = srd_inst_send_meta(next_di, key, data)) != SRD_OK)
+			return ret;
+	}
 
 	return SRD_OK;
 }
@@ -213,23 +220,24 @@ SRD_API int srd_session_metadata_set(struct srd_session *sess, int key,
  * in channel order, in the least amount of space possible. The default
  * channel set consists of all required channels + all optional channels.
  *
- * The size of a sample in inbuf is the unit size passed to
- * srd_inst_channel_set_all(). If no channel map has been configured, it is
- * the minimum number of bytes needed to store the default channels.
+ * The size of a sample in inbuf is 'unitsize' bytes. If no channel map
+ * has been configured, it is the minimum number of bytes needed to store
+ * the default channels.
  *
- * @param sess The session to use.
+ * @param sess The session to use. Must not be NULL.
  * @param start_samplenum The sample number of the first sample in this chunk.
  * @param end_samplenum The sample number of the last sample in this chunk.
- * @param inbuf Pointer to sample data.
- * @param inbuflen Length in bytes of the buffer.
+ * @param inbuf Pointer to sample data. Must not be NULL.
+ * @param inbuflen Length in bytes of the buffer. Must be > 0.
+ * @param unitsize The number of bytes per sample. Must be > 0.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
  *
- * @since 0.3.0
+ * @since 0.4.0
  */
 SRD_API int srd_session_send(struct srd_session *sess,
 		uint64_t start_samplenum, uint64_t end_samplenum,
-		const uint8_t *inbuf, uint64_t inbuflen)
+		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
 {
 	GSList *d;
 	int ret;
@@ -239,13 +247,9 @@ SRD_API int srd_session_send(struct srd_session *sess,
 		return SRD_ERR_ARG;
 	}
 
-	srd_dbg("Calling decode() on all instances with starting sample "
-			"number %" PRIu64 ", %" PRIu64 " bytes at 0x%p",
-			start_samplenum, inbuflen, inbuf);
-
 	for (d = sess->di_list; d; d = d->next) {
 		if ((ret = srd_inst_decode(d->data, start_samplenum,
-				end_samplenum, inbuf, inbuflen)) != SRD_OK)
+				end_samplenum, inbuf, inbuflen, unitsize)) != SRD_OK)
 			return ret;
 	}
 
@@ -312,11 +316,7 @@ SRD_API int srd_pd_output_callback_add(struct srd_session *sess,
 
 	srd_dbg("Registering new callback for output type %d.", output_type);
 
-	if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback)))) {
-		srd_err("Failed to g_malloc() struct srd_pd_callback.");
-		return SRD_ERR_MALLOC;
-	}
-
+	pd_cb = g_malloc(sizeof(struct srd_pd_callback));
 	pd_cb->output_type = output_type;
 	pd_cb->cb = cb;
 	pd_cb->cb_data = cb_data;
diff --git a/srd.c b/srd.c
index 599d190..344919a 100644
--- a/srd.c
+++ b/srd.c
@@ -18,9 +18,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <glib.h>
 
 /** @cond PRIVATE */
@@ -62,7 +62,7 @@ extern SRD_PRIV int max_session_id;
  *
  * @section sec_mailinglists Mailing lists
  *
- * There are two mailing lists for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a> and <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-commits">sigrok-commits</a>.
+ * There is one mailing list for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a>.
  *
  * @section sec_irc IRC
  *
@@ -95,6 +95,23 @@ extern SRD_PRIV int max_session_id;
  * @{
  */
 
+static int searchpath_add_xdg_dir(const char *datadir)
+{
+	char *decdir;
+	int ret;
+
+	decdir = g_build_filename(datadir, PACKAGE_TARNAME, "decoders", NULL);
+
+	if (g_file_test(decdir, G_FILE_TEST_IS_DIR))
+		ret = srd_decoder_searchpath_add(decdir);
+	else
+		ret = SRD_OK; /* just ignore non-existing directory */
+
+	g_free(decdir);
+
+	return ret;
+}
+
 /**
  * Initialize libsigrokdecode.
  *
@@ -124,8 +141,10 @@ extern SRD_PRIV int max_session_id;
  */
 SRD_API int srd_init(const char *path)
 {
+	const char *const *sys_datadirs;
+	const char *env_path;
+	size_t i;
 	int ret;
-	char *env_path;
 
 	if (max_session_id != -1) {
 		srd_err("libsigrokdecode is already initialized.");
@@ -138,13 +157,30 @@ SRD_API int srd_init(const char *path)
 	PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
 
 	/* Initialize the Python interpreter. */
-	Py_Initialize();
+	Py_InitializeEx(0);
 
-	/* Installed decoders. */
+	/* Locations relative to the XDG system data directories. */
+	sys_datadirs = g_get_system_data_dirs();
+	for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) {
+		ret = searchpath_add_xdg_dir(sys_datadirs[i-1]);
+		if (ret != SRD_OK) {
+			Py_Finalize();
+			return ret;
+		}
+	}
+#ifdef DECODERS_DIR
+	/* Hardcoded decoders install location, if defined. */
 	if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
 		Py_Finalize();
 		return ret;
 	}
+#endif
+	/* Location relative to the XDG user data directory. */
+	ret = searchpath_add_xdg_dir(g_get_user_data_dir());
+	if (ret != SRD_OK) {
+		Py_Finalize();
+		return ret;
+	}
 
 	/* Path specified by the user. */
 	if (path) {
@@ -155,7 +191,7 @@ SRD_API int srd_init(const char *path)
 	}
 
 	/* Environment variable overrides everything, for debugging. */
-	if ((env_path = getenv("SIGROKDECODE_DIR"))) {
+	if ((env_path = g_getenv("SIGROKDECODE_DIR"))) {
 		if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
 			Py_Finalize();
 			return ret;
@@ -183,12 +219,9 @@ SRD_API int srd_init(const char *path)
  */
 SRD_API int srd_exit(void)
 {
-	GSList *l;
-
 	srd_dbg("Exiting libsigrokdecode.");
 
-	for (l = sessions; l; l = l->next)
-		srd_session_destroy((struct srd_session *)l->data);
+	g_slist_foreach(sessions, (GFunc)srd_session_destroy, NULL);
 
 	srd_decoder_unload_all();
 	g_slist_free_full(searchpaths, g_free);
@@ -224,39 +257,26 @@ SRD_API int srd_exit(void)
 SRD_PRIV int srd_decoder_searchpath_add(const char *path)
 {
 	PyObject *py_cur_path, *py_item;
-	GString *new_path;
-	int wc_len, i;
-	wchar_t *wc_new_path;
-	char *item;
 
 	srd_dbg("Adding '%s' to module path.", path);
 
-	new_path = g_string_sized_new(256);
-	g_string_assign(new_path, path);
 	py_cur_path = PySys_GetObject("path");
-	for (i = 0; i < PyList_Size(py_cur_path); i++) {
-		g_string_append(new_path, G_SEARCHPATH_SEPARATOR_S);
-		py_item = PyList_GetItem(py_cur_path, i);
-		if (!PyUnicode_Check(py_item))
-			/* Shouldn't happen. */
-			continue;
-		if (py_str_as_str(py_item, &item) != SRD_OK)
-			continue;
-		g_string_append(new_path, item);
-		g_free(item);
-	}
+	if (!py_cur_path)
+		return SRD_ERR_PYTHON;
 
-	/* Convert to wide chars. */
-	wc_len = sizeof(wchar_t) * (new_path->len + 1);
-	if (!(wc_new_path = g_try_malloc(wc_len))) {
-		srd_dbg("malloc failed");
-		return SRD_ERR_MALLOC;
+	py_item = PyUnicode_FromString(path);
+	if (!py_item) {
+		srd_exception_catch("Failed to create Unicode object");
+		return SRD_ERR_PYTHON;
 	}
-	mbstowcs(wc_new_path, new_path->str, wc_len);
-	PySys_SetPath(wc_new_path);
-	g_string_free(new_path, TRUE);
-	g_free(wc_new_path);
-	searchpaths = g_slist_append(searchpaths, g_strdup(path));
+	if (PyList_Insert(py_cur_path, 0, py_item) < 0) {
+		srd_exception_catch("Failed to insert path element");
+		Py_DECREF(py_item);
+		return SRD_ERR_PYTHON;
+	}
+	Py_DECREF(py_item);
+
+	searchpaths = g_slist_prepend(searchpaths, g_strdup(path));
 
 	return SRD_OK;
 }
diff --git a/tests/check_core.c b/tests/core.c
similarity index 91%
rename from tests/check_core.c
rename to tests/core.c
index e5b7b35..670d9bd 100644
--- a/tests/check_core.c
+++ b/tests/core.c
@@ -18,21 +18,12 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "../libsigrokdecode.h" /* First, to avoid compiler warning. */
+#include <config.h>
+#include <libsigrokdecode.h> /* First, to avoid compiler warning. */
 #include <stdlib.h>
 #include <check.h>
 #include "lib.h"
 
-static void setup(void)
-{
-	/* Silence libsigrokdecode while the unit tests run. */
-	srd_log_loglevel_set(SRD_LOG_NONE);
-}
-
-static void teardown(void)
-{
-}
-
 /*
  * Check various basic init related things.
  *
@@ -104,7 +95,7 @@ Suite *suite_core(void)
 	s = suite_create("core");
 
 	tc = tcase_create("init_exit");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_init_exit);
 	tcase_add_test(tc, test_init_exit_2);
 	tcase_add_test(tc, test_init_exit_3);
diff --git a/tests/check_decoder.c b/tests/decoder.c
similarity index 72%
rename from tests/check_decoder.c
rename to tests/decoder.c
index 527845f..2b88785 100644
--- a/tests/check_decoder.c
+++ b/tests/decoder.c
@@ -18,21 +18,12 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "../libsigrokdecode.h" /* First, to avoid compiler warning. */
+#include <config.h>
+#include <libsigrokdecode.h> /* First, to avoid compiler warning. */
 #include <stdlib.h>
 #include <check.h>
 #include "lib.h"
 
-static void setup(void)
-{
-	/* Silence libsigrokdecode while the unit tests run. */
-	srd_log_loglevel_set(SRD_LOG_NONE);
-}
-
-static void teardown(void)
-{
-}
-
 /*
  * Check whether srd_decoder_load_all() works.
  * If it returns != SRD_OK (or segfaults) this test will fail.
@@ -41,7 +32,7 @@ START_TEST(test_load_all)
 {
 	int ret;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	ret = srd_decoder_load_all();
 	fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret);
 	srd_exit();
@@ -70,7 +61,7 @@ START_TEST(test_load)
 {
 	int ret;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	ret = srd_decoder_load("uart");
 	fail_unless(ret == SRD_OK, "srd_decoder_load(uart) failed: %d.", ret);
 	ret = srd_decoder_load("spi");
@@ -87,7 +78,7 @@ END_TEST
  */
 START_TEST(test_load_bogus)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	/* http://sigrok.org/bugzilla/show_bug.cgi?id=176 */
 	fail_unless(srd_decoder_load(NULL) != SRD_OK);
 	fail_unless(srd_decoder_load("") != SRD_OK);
@@ -110,7 +101,7 @@ END_TEST
  */
 START_TEST(test_load_valid_and_bogus)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	fail_unless(srd_decoder_load("") != SRD_OK);
 	fail_unless(srd_decoder_load("uart") == SRD_OK);
 	fail_unless(srd_decoder_load("") != SRD_OK);
@@ -131,7 +122,7 @@ START_TEST(test_load_multiple)
 {
 	int ret;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	ret = srd_decoder_load("uart");
 	fail_unless(ret == SRD_OK, "Loading uart PD 1x failed: %d", ret);
 	ret = srd_decoder_load("uart");
@@ -159,12 +150,120 @@ START_TEST(test_load_nonexisting_pd_dir)
 END_TEST
 
 /*
+ * Check whether srd_decoder_unload_all() works.
+ * If it returns != SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_all)
+{
+	int ret;
+
+	srd_init(DECODERS_TESTDIR);
+	ret = srd_decoder_load_all();
+	fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret);
+	ret = srd_decoder_unload_all();
+	fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret);
+	srd_exit();
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload_all() works without prior srd_init().
+ * If it returns != SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_all_no_init)
+{
+	int ret;
+
+	ret = srd_decoder_unload_all();
+	fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret);
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload_all() works multiple times.
+ * If it returns != SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_all_multiple)
+{
+	int ret, i;
+
+	srd_init(DECODERS_TESTDIR);
+	for (i = 0; i < 10; i++) {
+		ret = srd_decoder_load_all();
+		fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret);
+		ret = srd_decoder_unload_all();
+		fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret);
+	}
+	srd_exit();
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload_all() works multiple times (no load).
+ * If it returns != SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_all_multiple_noload)
+{
+	int ret, i;
+
+	srd_init(DECODERS_TESTDIR);
+	for (i = 0; i < 10; i++) {
+		ret = srd_decoder_unload_all();
+		fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret);
+	}
+	srd_exit();
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload() works.
+ * If it returns != SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload)
+{
+	int ret;
+	struct srd_decoder *dec;
+
+	srd_init(DECODERS_TESTDIR);
+	ret = srd_decoder_load("uart");
+	fail_unless(ret == SRD_OK, "srd_decoder_load(uart) failed: %d.", ret);
+	dec = srd_decoder_get_by_id("uart");
+	fail_unless(dec != NULL);
+	ret = srd_decoder_unload(dec);
+	fail_unless(ret == SRD_OK, "srd_decoder_unload() failed: %d.", ret);
+	srd_exit();
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload(NULL) fails.
+ * If it returns SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_null)
+{
+	srd_init(DECODERS_TESTDIR);
+	fail_unless(srd_decoder_unload(NULL) != SRD_OK);
+	srd_exit();
+}
+END_TEST
+
+/*
+ * Check whether srd_decoder_unload(NULL) fails without prior srd_init().
+ * If it returns SRD_OK (or segfaults) this test will fail.
+ */
+START_TEST(test_unload_null_no_init)
+{
+	fail_unless(srd_decoder_unload(NULL) != SRD_OK);
+}
+END_TEST
+
+/*
  * Check whether srd_decoder_list() returns a non-empty list.
  * If it returns an empty list (or segfaults) this test will fail.
  */
 START_TEST(test_decoder_list)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load_all();
 	fail_unless(srd_decoder_list() != NULL);
 	srd_exit();
@@ -178,7 +277,7 @@ END_TEST
  */
 START_TEST(test_decoder_list_no_load)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	fail_unless(srd_decoder_list() == NULL);
 	srd_exit();
 }
@@ -214,7 +313,7 @@ END_TEST
  */
 START_TEST(test_decoder_list_correct_numbers)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 0);
 	srd_decoder_load("spi");
 	fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 1);
@@ -234,7 +333,7 @@ END_TEST
  */
 START_TEST(test_get_by_id)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load("uart");
 	fail_unless(srd_decoder_get_by_id("uart") != NULL);
 	fail_unless(srd_decoder_get_by_id("can") == NULL);
@@ -251,7 +350,7 @@ END_TEST
  */
 START_TEST(test_get_by_id_multiple)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load("uart");
 	fail_unless(srd_decoder_get_by_id("uart") != NULL);
 	fail_unless(srd_decoder_get_by_id("uart") != NULL);
@@ -267,7 +366,7 @@ END_TEST
  */
 START_TEST(test_get_by_id_bogus)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	fail_unless(srd_decoder_get_by_id(NULL) == NULL);
 	fail_unless(srd_decoder_get_by_id("") == NULL);
 	fail_unless(srd_decoder_get_by_id(" ") == NULL);
@@ -291,7 +390,7 @@ START_TEST(test_doc_get)
 {
 	struct srd_decoder *dec;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load("uart");
 	dec = srd_decoder_get_by_id("uart");
 	fail_unless(srd_decoder_doc_get(dec) != NULL);
@@ -306,7 +405,7 @@ END_TEST
  */
 START_TEST(test_doc_get_null)
 {
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	fail_unless(srd_decoder_doc_get(NULL) == NULL);
 	srd_exit();
 }
@@ -320,7 +419,8 @@ Suite *suite_decoder(void)
 	s = suite_create("decoder");
 
 	tc = tcase_create("load");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_set_timeout(tc, 0);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_load_all);
 	tcase_add_test(tc, test_load_all_no_init);
 	tcase_add_test(tc, test_load);
@@ -330,8 +430,19 @@ Suite *suite_decoder(void)
 	tcase_add_test(tc, test_load_nonexisting_pd_dir);
 	suite_add_tcase(s, tc);
 
+	tc = tcase_create("unload");
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
+	tcase_add_test(tc, test_unload_all);
+	tcase_add_test(tc, test_unload_all_no_init);
+	tcase_add_test(tc, test_unload_all_multiple);
+	tcase_add_test(tc, test_unload_all_multiple_noload);
+	tcase_add_test(tc, test_unload);
+	tcase_add_test(tc, test_unload_null);
+	tcase_add_test(tc, test_unload_null_no_init);
+	suite_add_tcase(s, tc);
+
 	tc = tcase_create("list");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_decoder_list);
 	tcase_add_test(tc, test_decoder_list_no_load);
 	tcase_add_test(tc, test_decoder_list_no_init);
diff --git a/tests/check_inst.c b/tests/inst.c
similarity index 91%
rename from tests/check_inst.c
rename to tests/inst.c
index fccd2e1..d52793a 100644
--- a/tests/check_inst.c
+++ b/tests/inst.c
@@ -18,21 +18,12 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "../libsigrokdecode.h" /* First, to avoid compiler warning. */
+#include <config.h>
+#include <libsigrokdecode.h> /* First, to avoid compiler warning. */
 #include <stdlib.h>
 #include <check.h>
 #include "lib.h"
 
-static void setup(void)
-{
-	/* Silence libsigrokdecode while the unit tests run. */
-	srd_log_loglevel_set(SRD_LOG_NONE);
-}
-
-static void teardown(void)
-{
-}
-
 /*
  * Check whether srd_inst_new() works.
  * If it returns NULL (or segfaults) this test will fail.
@@ -42,7 +33,7 @@ START_TEST(test_inst_new)
 	struct srd_session *sess;
 	struct srd_decoder_inst *inst;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load("uart");
 	srd_session_new(&sess);
 	inst = srd_inst_new(sess, "uart", NULL);
@@ -62,7 +53,7 @@ START_TEST(test_inst_new_multiple)
 
 	inst1 = inst2 = inst3 = NULL;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load_all();
 	srd_session_new(&sess);
 
@@ -99,7 +90,7 @@ START_TEST(test_inst_option_set_empty)
 	struct srd_decoder_inst *inst;
 	GHashTable *options;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load_all();
 	srd_session_new(&sess);
 	inst = srd_inst_new(sess, "uart", NULL);
@@ -123,7 +114,7 @@ START_TEST(test_inst_option_set_bogus)
 	struct srd_decoder_inst *inst;
 	GHashTable *options;
 
-	srd_init(DECODERS_DIR);
+	srd_init(DECODERS_TESTDIR);
 	srd_decoder_load_all();
 	srd_session_new(&sess);
 	inst = srd_inst_new(sess, "uart", NULL);
@@ -158,13 +149,13 @@ Suite *suite_inst(void)
 	s = suite_create("inst");
 
 	tc = tcase_create("new");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_inst_new);
 	tcase_add_test(tc, test_inst_new_multiple);
 	suite_add_tcase(s, tc);
 
 	tc = tcase_create("option");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_inst_option_set_empty);
 	tcase_add_test(tc, test_inst_option_set_bogus);
 	suite_add_tcase(s, tc);
diff --git a/tests/lib.h b/tests/lib.h
index e5609d4..75380a1 100644
--- a/tests/lib.h
+++ b/tests/lib.h
@@ -21,6 +21,9 @@
 #ifndef LIBSIGROKDECODE_TESTS_LIB_H
 #define LIBSIGROKDECODE_TESTS_LIB_H
 
+void srdtest_setup(void);
+void srdtest_teardown(void);
+
 Suite *suite_core(void);
 Suite *suite_decoder(void);
 Suite *suite_inst(void);
diff --git a/tests/check_main.c b/tests/main.c
similarity index 85%
rename from tests/check_main.c
rename to tests/main.c
index 6af3c3f..b84b20e 100644
--- a/tests/check_main.c
+++ b/tests/main.c
@@ -18,11 +18,22 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "../libsigrokdecode.h" /* First, to avoid compiler warning. */
+#include <config.h>
+#include <libsigrokdecode.h> /* First, to avoid compiler warning. */
 #include <stdlib.h>
 #include <check.h>
 #include "lib.h"
 
+void srdtest_setup(void)
+{
+	/* Silence libsigrokdecode while the unit tests run. */
+	srd_log_loglevel_set(SRD_LOG_NONE);
+}
+
+void srdtest_teardown(void)
+{
+}
+
 int main(void)
 {
 	int ret;
diff --git a/tests/runtc.c b/tests/runtc.c
deleted file mode 100644
index cd3d449..0000000
--- a/tests/runtc.c
+++ /dev/null
@@ -1,837 +0,0 @@
-/*
- * This file is part of the libsigrokdecode project.
- *
- * Copyright (C) 2013 Bert Vermeulen <bert at biot.com>
- *
- * 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 3 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, see <http://www.gnu.org/licenses/>.
- */
-
-#include "../libsigrokdecode.h"
-#include <libsigrok/libsigrok.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <time.h>
-#include <sys/time.h>
-#include <sys/resource.h>
-#include <dirent.h>
-#include <glib.h>
-#ifdef __LINUX__
-#include <sched.h>
-#endif
-#include "../config.h"
-
-int debug = FALSE;
-int statistics = FALSE;
-char *coverage_report;
-
-struct channel {
-	char *name;
-	int channel;
-};
-
-struct option {
-	char *key;
-	char *value;
-};
-
-struct pd {
-	char *name;
-	GSList *channels;
-	GSList *options;
-};
-
-struct output {
-	char *pd;
-	int type;
-	char *class;
-	int class_idx;
-	char *outfile;
-	int outfd;
-};
-
-struct cvg {
-	int num_lines;
-	int num_missed;
-	float coverage;
-	GSList *missed_lines;
-};
-
-
-struct cvg *get_mod_cov(PyObject *py_cov, char *module_name);
-void cvg_add(struct cvg *dst, struct cvg *src);
-struct cvg *cvg_new(void);
-gboolean find_missed_line(struct cvg *cvg, char *linespec);
-
-
-static void logmsg(char *prefix, FILE *out, const char *format, va_list args)
-{
-	if (prefix)
-		fprintf(out, "%s", prefix);
-	vfprintf(out, format, args);
-	fprintf(out, "\n");
-}
-
-static void DBG(const char *format, ...)
-{
-	va_list args;
-
-	if (!debug)
-		return;
-	va_start(args, format);
-	logmsg("DBG: runtc: ", stdout, format, args);
-	va_end(args);
-}
-
-static void ERR(const char *format, ...)
-{
-	va_list args;
-
-	va_start(args, format);
-	logmsg("Error: ", stderr, format, args);
-	va_end(args);
-}
-
-static int sr_log(void *cb_data, int loglevel, const char *format, va_list args)
-{
-	(void)cb_data;
-
-	if (loglevel == SR_LOG_ERR || loglevel == SR_LOG_WARN)
-		logmsg("Error: sr: ", stderr, format, args);
-	else if (debug)
-		logmsg("DBG: sr: ", stdout, format, args);
-
-	return SRD_OK;
-}
-
-static int srd_log(void *cb_data, int loglevel, const char *format, va_list args)
-{
-	(void)cb_data;
-
-	if (loglevel == SRD_LOG_ERR || loglevel == SRD_LOG_WARN)
-		logmsg("Error: srd: ", stderr, format, args);
-	else if (debug)
-		logmsg("DBG: srd: ", stdout, format, args);
-
-	return SRD_OK;
-}
-
-static void usage(char *msg)
-{
-	if (msg)
-		fprintf(stderr, "%s\n", msg);
-
-	printf("Usage: runtc [-dPpoiOf]\n");
-	printf("  -d  Debug\n");
-	printf("  -P  <protocol decoder>\n");
-	printf("  -p  <channelname=channelnum> (optional)\n");
-	printf("  -o  <channeloption=value> (optional)\n");
-	printf("  -i <input file>\n");
-	printf("  -O <output-pd:output-type[:output-class]>\n");
-	printf("  -f <output file> (optional)\n");
-	printf("  -c <coverage report> (optional)\n");
-	exit(msg ? 1 : 0);
-
-}
-
-/* This is a neutered version of libsigrokdecode's py_str_as_str(). It
- * does no error checking, but then the only strings it processes are
- * generated by Python's repr(), so are known good. */
-static char *py_str_as_str(const PyObject *py_str)
-{
-	PyObject *py_encstr;
-	char *str, *outstr;
-
-	py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str, "utf-8", NULL);
-	str = PyBytes_AS_STRING(py_encstr);
-	outstr = g_strdup(str);
-	Py_DecRef(py_encstr);
-
-	return outstr;
-}
-
-static void srd_cb_py(struct srd_proto_data *pdata, void *cb_data)
-{
-	struct output *op;
-	PyObject *pydata, *pyrepr;
-	GString *out;
-	char *s;
-
-	DBG("Python output from %s", pdata->pdo->di->inst_id);
-	op = cb_data;
-	pydata = pdata->data;
-	DBG("ptr %p", pydata);
-
-	if (strcmp(pdata->pdo->di->inst_id, op->pd))
-		/* This is not the PD selected for output. */
-		return;
-
-	if (!(pyrepr = PyObject_Repr(pydata))) {
-		ERR("Invalid Python object.");
-		return;
-	}
-	s = py_str_as_str(pyrepr);
-	Py_DecRef(pyrepr);
-
-	/* Output format for testing is '<ss>-<es> <inst-id>: <repr>\n' */
-	out = g_string_sized_new(128);
-	g_string_printf(out, "%"PRIu64"-%"PRIu64" %s: %s\n",
-			pdata->start_sample, pdata->end_sample,
-			pdata->pdo->di->inst_id, s);
-	g_free(s);
-	if (write(op->outfd, out->str, out->len) == -1)
-		ERR("SRD_OUTPUT_PYTHON callback write failure!");
-	DBG("wrote '%s'", out->str);
-	g_string_free(out, TRUE);
-
-}
-
-static void srd_cb_bin(struct srd_proto_data *pdata, void *cb_data)
-{
-	struct srd_proto_data_binary *pdb;
-	struct output *op;
-	GString *out;
-	unsigned int i;
-
-	DBG("Binary output from %s", pdata->pdo->di->inst_id);
-	op = cb_data;
-	pdb = pdata->data;
-
-	if (strcmp(pdata->pdo->di->inst_id, op->pd))
-		/* This is not the PD selected for output. */
-		return;
-
-	if (op->class_idx != -1 && op->class_idx != pdb->bin_class)
-		/*
-		 * This output takes a specific binary class,
-		 * but not the one that just came in.
-		 */
-		return;
-
-	out = g_string_sized_new(128);
-	g_string_printf(out, "%"PRIu64"-%"PRIu64" %s:",
-			pdata->start_sample, pdata->end_sample,
-			pdata->pdo->di->inst_id);
-	for (i = 0; i < pdb->size; i++) {
-		g_string_append_printf(out, " %.2x", pdb->data[i]);
-	}
-	g_string_append(out, "\n");
-	if (write(op->outfd, out->str, out->len) == -1)
-		ERR("SRD_OUTPUT_BINARY callback write failure!");
-
-}
-
-static void srd_cb_ann(struct srd_proto_data *pdata, void *cb_data)
-{
-	struct srd_decoder *dec;
-	struct srd_proto_data_annotation *pda;
-	struct output *op;
-	GString *line;
-	int i;
-	char **dec_ann;
-
-	DBG("Annotation output from %s", pdata->pdo->di->inst_id);
-	op = cb_data;
-	pda = pdata->data;
-	dec = pdata->pdo->di->decoder;
-	if (strcmp(pdata->pdo->di->inst_id, op->pd))
-		/* This is not the PD selected for output. */
-		return;
-
-	if (op->class_idx != -1 && op->class_idx != pda->ann_format)
-		/*
-		 * This output takes a specific annotation class,
-		 * but not the one that just came in.
-		 */
-		return;
-
-	dec_ann = g_slist_nth_data(dec->annotations, pda->ann_format);
-	line = g_string_sized_new(256);
-	g_string_printf(line, "%"PRIu64"-%"PRIu64" %s: %s:",
-			pdata->start_sample, pdata->end_sample,
-			pdata->pdo->di->inst_id, dec_ann[0]);
-	for (i = 0; pda->ann_text[i]; i++)
-		g_string_append_printf(line, " \"%s\"", pda->ann_text[i]);
-	g_string_append(line, "\n");
-	if (write(op->outfd, line->str, line->len) == -1)
-		ERR("SRD_OUTPUT_ANN callback write failure!");
-	g_string_free(line, TRUE);
-
-}
-
-static void sr_cb(const struct sr_dev_inst *sdi,
-		const struct sr_datafeed_packet *packet, void *cb_data)
-{
-	const struct sr_datafeed_logic *logic;
-	struct srd_session *sess;
-	GVariant *gvar;
-	uint64_t samplerate;
-	int num_samples;
-	static int samplecnt = 0;
-
-	sess = cb_data;
-
-	switch (packet->type) {
-	case SR_DF_HEADER:
-		DBG("Received SR_DF_HEADER");
-		if (sr_config_get(sdi->driver, sdi, NULL, SR_CONF_SAMPLERATE,
-				&gvar) != SR_OK) {
-			ERR("Getting samplerate failed");
-			break;
-		}
-		samplerate = g_variant_get_uint64(gvar);
-		g_variant_unref(gvar);
-		if (srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE,
-				g_variant_new_uint64(samplerate)) != SRD_OK) {
-			ERR("Setting samplerate failed");
-			break;
-		}
-		if (srd_session_start(sess) != SRD_OK) {
-			ERR("Session start failed");
-			break;
-		}
-		break;
-	case SR_DF_LOGIC:
-		logic = packet->payload;
-		num_samples = logic->length / logic->unitsize;
-		DBG("Received SR_DF_LOGIC: %d samples", num_samples);
-		srd_session_send(sess, samplecnt, samplecnt + num_samples,
-				logic->data, logic->length);
-		samplecnt += logic->length / logic->unitsize;
-		break;
-	case SR_DF_END:
-		DBG("Received SR_DF_END");
-		break;
-	}
-
-}
-
-static int run_testcase(char *infile, GSList *pdlist, struct output *op)
-{
-	struct srd_session *sess;
-	struct srd_decoder *dec;
-	struct srd_decoder_inst *di, *prev_di;
-	srd_pd_output_callback cb;
-	struct pd *pd;
-	struct channel *channel;
-	struct option *option;
-	GVariant *gvar;
-	GHashTable *channels, *opts;
-	GSList *pdl, *l;
-	int idx;
-	int max_channel;
-	char **decoder_class;
-
-	if (op->outfile) {
-		if ((op->outfd = open(op->outfile, O_CREAT|O_WRONLY, 0600)) == -1) {
-			ERR("Unable to open %s for writing: %s", op->outfile,
-					strerror(errno));
-			return FALSE;
-		}
-	}
-
-	if (sr_session_load(infile) != SR_OK)
-		return FALSE;
-
-	if (srd_session_new(&sess) != SRD_OK)
-		return FALSE;
-	sr_session_datafeed_callback_add(sr_cb, sess);
-	switch (op->type) {
-	case SRD_OUTPUT_ANN:
-		cb = srd_cb_ann;
-		break;
-	case SRD_OUTPUT_BINARY:
-		cb = srd_cb_bin;
-		break;
-	case SRD_OUTPUT_PYTHON:
-		cb = srd_cb_py;
-		break;
-	default:
-		return FALSE;
-	}
-	srd_pd_output_callback_add(sess, op->type, cb, op);
-
-	prev_di = NULL;
-	pd = NULL;
-	for (pdl = pdlist; pdl; pdl = pdl->next) {
-		pd = pdl->data;
-		if (srd_decoder_load(pd->name) != SRD_OK)
-			return FALSE;
-
-		/* Instantiate decoder and pass in options. */
-		opts = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
-				(GDestroyNotify)g_variant_unref);
-		for (l = pd->options; l; l = l->next) {
-			option = l->data;
-			g_hash_table_insert(opts, option->key, option->value);
-		}
-		if (!(di = srd_inst_new(sess, pd->name, opts)))
-			return FALSE;
-		g_hash_table_destroy(opts);
-
-		/* Map channels. */
-		if (pd->channels) {
-			channels = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
-					(GDestroyNotify)g_variant_unref);
-			max_channel = 0;
-			for (l = pd->channels; l; l = l->next) {
-				channel = l->data;
-				if (channel->channel > max_channel)
-					max_channel = channel->channel;
-				gvar = g_variant_new_int32(channel->channel);
-				g_variant_ref_sink(gvar);
-				g_hash_table_insert(channels, channel->name, gvar);
-			}
-			if (srd_inst_channel_set_all(di, channels,
-					(max_channel + 8) / 8) != SRD_OK)
-				return FALSE;
-			g_hash_table_destroy(channels);
-		}
-
-		/* If this is not the first decoder in the list, stack it
-		 * on top of the previous one. */
-		if (prev_di) {
-			if (srd_inst_stack(sess, prev_di, di) != SRD_OK) {
-				ERR("Failed to stack decoder instances.");
-				return FALSE;
-			}
-		}
-		prev_di = di;
-	}
-
-	/* Resolve top decoder's class index, so we can match. */
-	dec = srd_decoder_get_by_id(pd->name);
-	if (op->class) {
-		if (op->type == SRD_OUTPUT_ANN)
-			l = dec->annotations;
-		else if (op->type == SRD_OUTPUT_BINARY)
-			l = dec->binary;
-		else
-			/* Only annotations and binary can have a class. */
-			return FALSE;
-		idx = 0;
-		while (l) {
-			decoder_class = l->data;
-			if (!strcmp(decoder_class[0], op->class)) {
-				op->class_idx = idx;
-				break;
-			} else
-				idx++;
-			l = l->next;
-		}
-		if (op->class_idx == -1) {
-			ERR("Output class '%s' not found in decoder %s.",
-					op->class, pd->name);
-			return FALSE;
-		} else
-			DBG("Class %s index is %d", op->class, op->class_idx);
-	}
-
-	sr_session_start();
-	sr_session_run();
-	sr_session_stop();
-
-	srd_session_destroy(sess);
-
-	if (op->outfile)
-		close(op->outfd);
-
-	return TRUE;
-}
-
-static PyObject *start_coverage(GSList *pdlist)
-{
-	PyObject *py_mod, *py_pdlist, *py_pd, *py_func, *py_args, *py_kwargs, *py_cov;
-	GSList *l;
-	struct pd *pd;
-
-	DBG("Starting coverage.");
-
-	if (!(py_mod = PyImport_ImportModule("coverage")))
-		return NULL;
-
-	if (!(py_pdlist = PyList_New(0)))
-		return NULL;
-	for (l = pdlist; l; l = l->next) {
-		pd = l->data;
-		py_pd = PyUnicode_FromFormat("*/%s/*.py", pd->name);
-		if (PyList_Append(py_pdlist, py_pd) < 0)
-			return NULL;
-		Py_DecRef(py_pd);
-	}
-	if (!(py_func = PyObject_GetAttrString(py_mod, "coverage")))
-		return NULL;
-	if (!(py_args = PyTuple_New(0)))
-		return NULL;
-	if (!(py_kwargs = Py_BuildValue("{sO}", "include", py_pdlist)))
-		return NULL;
-	if (!(py_cov = PyObject_Call(py_func, py_args, py_kwargs)))
-		return NULL;
-	if (!(PyObject_CallMethod(py_cov, "start", NULL)))
-		return NULL;
-	Py_DecRef(py_pdlist);
-	Py_DecRef(py_args);
-	Py_DecRef(py_kwargs);
-	Py_DecRef(py_func);
-
-	return py_cov;
-}
-
-struct cvg *get_mod_cov(PyObject *py_cov, char *module_name)
-{
-	PyObject *py_mod, *py_pathlist, *py_path, *py_func, *py_pd;
-	PyObject *py_result, *py_missed, *py_item;
-	DIR *d;
-	struct dirent *de;
-	struct cvg *cvg_mod;
-	int num_lines, num_missed, linenum, i, j;
-	char *path, *linespec;
-
-	if (!(py_mod = PyImport_ImportModule(module_name)))
-		return NULL;
-
-	cvg_mod = NULL;
-	py_pathlist = PyObject_GetAttrString(py_mod, "__path__");
-	for (i = 0; i < PyList_Size(py_pathlist); i++) {
-		py_path = PyList_GetItem(py_pathlist, i);
-        PyUnicode_FSConverter(PyList_GetItem(py_pathlist, i), &py_path);
-		path = PyBytes_AS_STRING(py_path);
-		if (!(d = opendir(path))) {
-			ERR("Invalid module path '%s'", path);
-			return NULL;
-		}
-		while ((de = readdir(d))) {
-			if (strncmp(de->d_name + strlen(de->d_name) - 3, ".py", 3))
-				continue;
-
-			if (!(py_func = PyObject_GetAttrString(py_cov, "analysis2")))
-				return NULL;
-			if (!(py_pd = PyUnicode_FromFormat("%s/%s", path, de->d_name)))
-				return NULL;
-			if (!(py_result = PyObject_CallFunction(py_func, "O", py_pd)))
-				return NULL;
-			Py_DecRef(py_pd);
-			Py_DecRef(py_func);
-
-			if (!cvg_mod)
-				cvg_mod = cvg_new();
-			if (PyTuple_Size(py_result) != 5) {
-				ERR("Invalid result from coverage of '%s/%s'", path, de->d_name);
-				return NULL;
-			}
-			num_lines = PyList_Size(PyTuple_GetItem(py_result, 1));
-			py_missed = PyTuple_GetItem(py_result, 3);
-			num_missed = PyList_Size(py_missed);
-			cvg_mod->num_lines += num_lines;
-			cvg_mod->num_missed += num_missed;
-			for (j = 0; j < num_missed; j++) {
-				py_item = PyList_GetItem(py_missed, j);
-				linenum = PyLong_AsLong(py_item);
-				linespec = g_strdup_printf("%s/%s:%d", module_name,
-						de->d_name, linenum);
-				cvg_mod->missed_lines = g_slist_append(cvg_mod->missed_lines, linespec);
-			}
-			DBG("Coverage for %s/%s: %d lines, %d missed.",
-					module_name, de->d_name, num_lines, num_missed);
-			Py_DecRef(py_result);
-		}
-	}
-	if (cvg_mod->num_lines)
-		cvg_mod->coverage = 100 - ((float)cvg_mod->num_missed / (float)cvg_mod->num_lines * 100);
-
-	Py_DecRef(py_mod);
-    Py_DecRef(py_path);
-
-	return cvg_mod;
-}
-
-struct cvg *cvg_new(void)
-{
-	struct cvg *cvg;
-
-	cvg = calloc(1, sizeof(struct cvg));
-
-	return cvg;
-}
-
-gboolean find_missed_line(struct cvg *cvg, char *linespec)
-{
-	GSList *l;
-
-	for (l = cvg->missed_lines; l; l = l->next)
-		if (!strcmp(l->data, linespec))
-			return TRUE;
-
-	return FALSE;
-}
-
-void cvg_add(struct cvg *dst, struct cvg *src)
-{
-	GSList *l;
-	char *linespec;
-
-
-	dst->num_lines += src->num_lines;
-	dst->num_missed += src->num_missed;
-	for (l = src->missed_lines; l; l = l->next) {
-		linespec = l->data;
-		if (!find_missed_line(dst, linespec))
-			dst->missed_lines = g_slist_append(dst->missed_lines, linespec);
-	}
-
-}
-
-static int report_coverage(PyObject *py_cov, GSList *pdlist)
-{
-	PyObject *py_func, *py_mod, *py_args, *py_kwargs, *py_outfile, *py_pct;
-	GSList *l, *ml;
-	struct pd *pd;
-	struct cvg *cvg_mod, *cvg_all;
-	float total_coverage;
-	int lines, missed, cnt;
-
-	DBG("Making coverage report.");
-
-	/* Get coverage for each module in the stack. */
-	lines = missed = 0;
-	cvg_all = cvg_new();
-	for (cnt = 0, l = pdlist; l; l = l->next, cnt++) {
-		pd = l->data;
-		if (!(cvg_mod = get_mod_cov(py_cov, pd->name)))
-			return FALSE;
-		printf("coverage: scope=%s coverage=%.0f%% lines=%d missed=%d "
-				"missed_lines=", pd->name, cvg_mod->coverage,
-				cvg_mod->num_lines, cvg_mod->num_missed);
-		for (ml = cvg_mod->missed_lines; ml; ml = ml->next) {
-			if (ml != cvg_mod->missed_lines)
-				printf(",");
-			printf("%s", (char *)ml->data);
-		}
-		printf("\n");
-		lines += cvg_mod->num_lines;
-		missed += cvg_mod->num_missed;
-		cvg_add(cvg_all, cvg_mod);
-		DBG("Coverage for module %s: %d lines, %d missed", pd->name,
-				cvg_mod->num_lines, cvg_mod->num_missed);
-	}
-	lines /= cnt;
-	missed /= cnt;
-	total_coverage = 100 - ((float)missed / (float)lines * 100);
-
-	/* Machine-readable stats on stdout. */
-	printf("coverage: scope=all coverage=%.0f%% lines=%d missed=%d\n",
-			total_coverage, cvg_all->num_lines, cvg_all->num_missed);
-
-
-	/* Write text report to file. */
-	/* io.open(coverage_report, "w") */
-	if (!(py_mod = PyImport_ImportModule("io")))
-		return FALSE;
-	if (!(py_func = PyObject_GetAttrString(py_mod, "open")))
-		return FALSE;
-	if (!(py_args = PyTuple_New(0)))
-		return FALSE;
-	if (!(py_kwargs = Py_BuildValue("{ssss}", "file", coverage_report,
-			"mode", "w")))
-		return FALSE;
-	if (!(py_outfile = PyObject_Call(py_func, py_args, py_kwargs)))
-		return FALSE;
-	Py_DecRef(py_kwargs);
-	Py_DecRef(py_func);
-
-	/* py_cov.report(file=py_outfile) */
-	if (!(py_func = PyObject_GetAttrString(py_cov, "report")))
-		return FALSE;
-	if (!(py_kwargs = Py_BuildValue("{sO}", "file", py_outfile)))
-		return FALSE;
-	if (!(py_pct = PyObject_Call(py_func, py_args, py_kwargs)))
-		return FALSE;
-	Py_DecRef(py_pct);
-	Py_DecRef(py_kwargs);
-	Py_DecRef(py_func);
-
-	/* py_outfile.close() */
-	if (!(py_func = PyObject_GetAttrString(py_outfile, "close")))
-		return FALSE;
-	if (!PyObject_Call(py_func, py_args, NULL))
-		return FALSE;
-	Py_DecRef(py_outfile);
-	Py_DecRef(py_func);
-	Py_DecRef(py_args);
-	Py_DecRef(py_mod);
-
-	return TRUE;
-}
-
-int main(int argc, char **argv)
-{
-	struct sr_context *ctx;
-	PyObject *coverage;
-	GSList *pdlist;
-	struct pd *pd;
-	struct channel *channel;
-	struct option *option;
-	struct output *op;
-	int ret;
-	char c, *opt_infile, **kv, **opstr;
-
-	op = malloc(sizeof(struct output));
-	op->pd = NULL;
-	op->type = -1;
-	op->class = NULL;
-	op->class_idx = -1;
-	op->outfd = 1;
-
-	pdlist = NULL;
-	opt_infile = NULL;
-	pd = NULL;
-	coverage = NULL;
-	while ((c = getopt(argc, argv, "dP:p:o:i:O:f:c:S")) != -1) {
-		switch(c) {
-		case 'd':
-			debug = TRUE;
-			break;
-		case 'P':
-			pd = g_malloc(sizeof(struct pd));
-			pd->name = g_strdup(optarg);
-			pd->channels = pd->options = NULL;
-			pdlist = g_slist_append(pdlist, pd);
-			break;
-		case 'p':
-		case 'o':
-			if (g_slist_length(pdlist) == 0) {
-				/* No previous -P. */
-				ERR("Syntax error at '%s'", optarg);
-				usage(NULL);
-			}
-			kv = g_strsplit(optarg, "=", 0);
-			if (!kv[0] || (!kv[1] || kv[2])) {
-				/* Need x=y. */
-				ERR("Syntax error at '%s'", optarg);
-				g_strfreev(kv);
-				usage(NULL);
-			}
-			if (c == 'p') {
-				channel = malloc(sizeof(struct channel));
-				channel->name = g_strdup(kv[0]);
-				channel->channel = strtoul(kv[1], 0, 10);
-				/* Apply to last PD. */
-				pd->channels = g_slist_append(pd->channels, channel);
-			} else {
-				option = malloc(sizeof(struct option));
-				option->key = g_strdup(kv[0]);
-				option->value = g_strdup(kv[1]);
-				/* Apply to last PD. */
-				pd->options = g_slist_append(pd->options, option);
-			}
-			break;
-		case 'i':
-			opt_infile = optarg;
-			break;
-		case 'O':
-			opstr = g_strsplit(optarg, ":", 0);
-			if (!opstr[0] || !opstr[1]) {
-				/* Need at least abc:def. */
-				ERR("Syntax error at '%s'", optarg);
-				g_strfreev(opstr);
-				usage(NULL);
-			}
-			op->pd = g_strdup(opstr[0]);
-			if (!strcmp(opstr[1], "annotation"))
-				op->type = SRD_OUTPUT_ANN;
-			else if (!strcmp(opstr[1], "binary"))
-				op->type = SRD_OUTPUT_BINARY;
-			else if (!strcmp(opstr[1], "python"))
-				op->type = SRD_OUTPUT_PYTHON;
-			else {
-				ERR("Unknown output type '%s'", opstr[1]);
-				g_strfreev(opstr);
-				usage(NULL);
-			}
-			if (opstr[2])
-				op->class = g_strdup(opstr[2]);
-			g_strfreev(opstr);
-			break;
-		case 'f':
-			op->outfile = g_strdup(optarg);
-			op->outfd = -1;
-			break;
-		case 'c':
-			coverage_report = optarg;
-			break;
-		case 'S':
-			statistics = TRUE;
-			break;
-		default:
-			usage(NULL);
-		}
-	}
-	if (argc > optind)
-		usage(NULL);
-	if (g_slist_length(pdlist) == 0)
-		usage(NULL);
-	if (!opt_infile)
-		usage(NULL);
-	if (!op->pd || op->type == -1)
-		usage(NULL);
-
-	sr_log_callback_set(sr_log, NULL);
-	if (sr_init(&ctx) != SR_OK)
-		return 1;
-
-	srd_log_callback_set(srd_log, NULL);
-	if (srd_init(DECODERS_DIR) != SRD_OK)
-		return 1;
-
-	if (coverage_report) {
-		if (!(coverage = start_coverage(pdlist))) {
-			DBG("Failed to start coverage.");
-			if (PyErr_Occurred()) {
-				PyErr_PrintEx(0);
-				PyErr_Clear();
-			}
-		}
-	}
-
-	ret = 0;
-	if (!run_testcase(opt_infile, pdlist, op))
-		ret = 1;
-
-	if (coverage) {
-		DBG("Stopping coverage.");
-
-		if (!(PyObject_CallMethod(coverage, "stop", NULL)))
-			ERR("Failed to stop coverage.");
-		else if (!(report_coverage(coverage, pdlist)))
-			ERR("Failed to make coverage report.");
-		else
-			DBG("Coverage report in %s", coverage_report);
-
-		if (PyErr_Occurred()) {
-			PyErr_PrintEx(0);
-			PyErr_Clear();
-		}
-		Py_DecRef(coverage);
-	}
-
-	srd_exit();
-	sr_exit(ctx);
-
-	return ret;
-}
diff --git a/tests/check_session.c b/tests/session.c
similarity index 93%
rename from tests/check_session.c
rename to tests/session.c
index f411854..0d352bd 100644
--- a/tests/check_session.c
+++ b/tests/session.c
@@ -18,23 +18,14 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
-#include "../libsigrokdecode.h" /* First, to avoid compiler warning. */
-#include "../libsigrokdecode-internal.h"
+#include <config.h>
+#include <libsigrokdecode-internal.h> /* First, to avoid compiler warning. */
+#include <libsigrokdecode.h>
 #include <stdint.h>
 #include <stdlib.h>
 #include <check.h>
 #include "lib.h"
 
-static void setup(void)
-{
-	/* Silence libsigrokdecode while the unit tests run. */
-	srd_log_loglevel_set(SRD_LOG_NONE);
-}
-
-static void teardown(void)
-{
-}
-
 /*
  * Check whether srd_session_new() works.
  * If it returns != SRD_OK (or segfaults) this test will fail.
@@ -214,7 +205,7 @@ START_TEST(test_session_metadata_set_bogus)
 	srd_init(NULL);
 	srd_session_new(&sess);
 
-	/* Incorrect gvariant type (currently only uint64 is used). */
+	/* Incorrect GVariant type (currently only uint64 is used). */
 	conf_check_fail_str(sess, SRD_CONF_SAMPLERATE, "");
 	conf_check_fail_str(sess, SRD_CONF_SAMPLERATE, "Foo");
 
@@ -242,7 +233,7 @@ Suite *suite_session(void)
 	s = suite_create("session");
 
 	tc = tcase_create("new_destroy");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_session_new);
 	tcase_add_test(tc, test_session_new_bogus);
 	tcase_add_test(tc, test_session_new_multiple);
@@ -251,7 +242,7 @@ Suite *suite_session(void)
 	suite_add_tcase(s, tc);
 
 	tc = tcase_create("config");
-	tcase_add_checked_fixture(tc, setup, teardown);
+	tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown);
 	tcase_add_test(tc, test_session_metadata_set);
 	tcase_add_test(tc, test_session_metadata_set_bogus);
 	suite_add_tcase(s, tc);
diff --git a/tools/install-decoders b/tools/install-decoders
index 465c70e..3772bd5 100755
--- a/tools/install-decoders
+++ b/tools/install-decoders
@@ -24,7 +24,21 @@ from shutil import copy
 from getopt import getopt
 
 
-def install(srcdir, dstdir):
+_inst_pp_col_max = 80
+_inst_pp_col = 0
+def _install_pretty_print(item):
+    """Pretty print an install item. Enforce maximum line width."""
+    global _inst_pp_col
+    if item is None:
+        _inst_pp_col = 0
+        return
+    _inst_pp_col += len(item)
+    if _inst_pp_col > _inst_pp_col_max:
+        print()
+        _inst_pp_col = len(item)
+    print(item, end = "")
+
+def install(srcdir, dstdir, s):
     worklist = []
     for pd in os.listdir(srcdir):
         pd_dir = srcdir + '/' + pd
@@ -39,17 +53,13 @@ def install(srcdir, dstdir):
                 install_list.extend(config_get_extra_install(pd_file))
             elif f[-3:] == '.py':
                 install_list.append(f)
-        worklist.append((pd, pd_dir, install_list))
+        if install_list:
+            worklist.append((pd, pd_dir, install_list))
 
-    print("Installing %d protocol decoders:" % len(worklist))
-    col = 0
+    worklist.sort()
+    print("Installing %d %s:" % (len(worklist), s))
     for pd, pd_dir, install_list in worklist:
-        msg = pd + ' '
-        if (col + len(msg) > 80):
-            print()
-            col = 0
-        print(msg, end='')
-        col += len(msg)
+        _install_pretty_print("{} ".format(pd))
         pd_dst = os.path.join(dstdir, pd)
         try:
             os.mkdir(pd_dst)
@@ -61,6 +71,7 @@ def install(srcdir, dstdir):
         for f in install_list:
             copy(os.path.join(pd_dir, f), pd_dst)
     print()
+    _install_pretty_print(None)
 
 
 def config_get_extra_install(config_file):
@@ -107,6 +118,7 @@ except Exception as e:
 if len(args) != 0 or dst is None:
     usage()
 
-install(src, dst)
+install(src, dst, 'protocol decoders')
+install(src + '/common', dst + '/common', 'common modules')
 
 
diff --git a/type_decoder.c b/type_decoder.c
index 11c8ec0..228cd44 100644
--- a/type_decoder.c
+++ b/type_decoder.c
@@ -17,22 +17,28 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <inttypes.h>
 
 typedef struct {
         PyObject_HEAD
 } srd_Decoder;
 
-/* This is only used for nicer srd_dbg() output. */
-static const char *OUTPUT_TYPES[] = {
-	"OUTPUT_ANN",
-	"OUTPUT_PYTHON",
-	"OUTPUT_BINARY",
-	"OUTPUT_META",
-};
+/* This is only used for nicer srd_dbg() output.
+ */
+static const char *output_type_name(unsigned int idx)
+{
+	static const char names[][16] = {
+		"OUTPUT_ANN",
+		"OUTPUT_PYTHON",
+		"OUTPUT_BINARY",
+		"OUTPUT_META",
+		"(invalid)"
+	};
+	return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
+}
 
 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
 		struct srd_proto_data *pdata)
@@ -40,27 +46,27 @@ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
 	PyObject *py_tmp;
 	struct srd_pd_output *pdo;
 	struct srd_proto_data_annotation *pda;
-	int ann_format;
+	int ann_class;
 	char **ann_text;
 
-	/* Should be a list of [annotation format, [string, ...]]. */
-	if (!PyList_Check(obj) && !PyTuple_Check(obj)) {
-		srd_err("Protocol decoder %s submitted %s instead of list.",
-			di->decoder->name, obj->ob_type->tp_name);
+	/* Should be a list of [annotation class, [string, ...]]. */
+	if (!PyList_Check(obj)) {
+		srd_err("Protocol decoder %s submitted an annotation that"
+			" is not a list", di->decoder->name);
 		return SRD_ERR_PYTHON;
 	}
 
 	/* Should have 2 elements. */
 	if (PyList_Size(obj) != 2) {
 		srd_err("Protocol decoder %s submitted annotation list with "
-			"%d elements instead of 2", di->decoder->name,
+			"%zd elements instead of 2", di->decoder->name,
 			PyList_Size(obj));
 		return SRD_ERR_PYTHON;
 	}
 
 	/*
 	 * The first element should be an integer matching a previously
-	 * registered annotation format.
+	 * registered annotation class.
 	 */
 	py_tmp = PyList_GetItem(obj, 0);
 	if (!PyLong_Check(py_tmp)) {
@@ -68,10 +74,10 @@ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
 			"first element was not an integer.", di->decoder->name);
 		return SRD_ERR_PYTHON;
 	}
-	ann_format = PyLong_AsLong(py_tmp);
-	if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_format))) {
+	ann_class = PyLong_AsLong(py_tmp);
+	if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
 		srd_err("Protocol decoder %s submitted data to unregistered "
-			"annotation format %d.", di->decoder->name, ann_format);
+			"annotation class %d.", di->decoder->name, ann_class);
 		return SRD_ERR_PYTHON;
 	}
 
@@ -88,9 +94,8 @@ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
 		return SRD_ERR_PYTHON;
 	}
 
-	if (!(pda = g_try_malloc(sizeof(struct srd_proto_data_annotation))))
-		return SRD_ERR_MALLOC;
-	pda->ann_format = ann_format;
+	pda = g_malloc(sizeof(struct srd_proto_data_annotation));
+	pda->ann_class = ann_class;
 	pda->ann_text = ann_text;
 	pdata->data = pda;
 
@@ -106,26 +111,25 @@ static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
 	int bin_class;
 	char *class_name, *buf;
 
-	/* Should be a tuple of (binary class, bytes). */
-	if (!PyTuple_Check(obj)) {
-		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
-				"%s instead of tuple.", di->decoder->name,
-				obj->ob_type->tp_name);
+	/* Should be a list of [binary class, bytes]. */
+	if (!PyList_Check(obj)) {
+		srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
+			di->decoder->name);
 		return SRD_ERR_PYTHON;
 	}
 
 	/* Should have 2 elements. */
-	if (PyTuple_Size(obj) != 2) {
-		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple "
-				"with %d elements instead of 2", di->decoder->name,
+	if (PyList_Size(obj) != 2) {
+		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
+				"with %zd elements instead of 2", di->decoder->name,
 				PyList_Size(obj));
 		return SRD_ERR_PYTHON;
 	}
 
 	/* The first element should be an integer. */
-	py_tmp = PyTuple_GetItem(obj, 0);
+	py_tmp = PyList_GetItem(obj, 0);
 	if (!PyLong_Check(py_tmp)) {
-		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
+		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
 			"but first element was not an integer.", di->decoder->name);
 		return SRD_ERR_PYTHON;
 	}
@@ -137,9 +141,9 @@ static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
 	}
 
 	/* Second element should be bytes. */
-	py_tmp = PyTuple_GetItem(obj, 1);
+	py_tmp = PyList_GetItem(obj, 1);
 	if (!PyBytes_Check(py_tmp)) {
-		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
+		srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
 			"but second element was not bytes.", di->decoder->name);
 		return SRD_ERR_PYTHON;
 	}
@@ -151,8 +155,7 @@ static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
 		return SRD_ERR_PYTHON;
 	}
 
-	if (!(pdb = g_try_malloc(sizeof(struct srd_proto_data_binary))))
-		return SRD_ERR_MALLOC;
+	pdb = g_malloc(sizeof(struct srd_proto_data_binary));
 	if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
 		return SRD_ERR_PYTHON;
 	pdb->bin_class = bin_class;
@@ -173,7 +176,7 @@ static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
 	if (pdata->pdo->meta_type == G_VARIANT_TYPE_INT64) {
 		if (!PyLong_Check(obj)) {
 			PyErr_Format(PyExc_TypeError, "This output was registered "
-					"as 'int', but '%s' was passed.", obj->ob_type->tp_name);
+					"as 'int', but something else was passed.");
 			return SRD_ERR_PYTHON;
 		}
 		intvalue = PyLong_AsLongLong(obj);
@@ -183,7 +186,7 @@ static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
 	} else if (pdata->pdo->meta_type == G_VARIANT_TYPE_DOUBLE) {
 		if (!PyFloat_Check(obj)) {
 			PyErr_Format(PyExc_TypeError, "This output was registered "
-					"as 'float', but '%s' was passed.", obj->ob_type->tp_name);
+					"as 'float', but something else was passed.");
 			return SRD_ERR_PYTHON;
 		}
 		dvalue = PyFloat_AsDouble(obj);
@@ -231,12 +234,9 @@ static PyObject *Decoder_put(PyObject *self, PyObject *args)
 
 	srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
 		 di->inst_id, start_sample, end_sample,
-		 OUTPUT_TYPES[pdo->output_type], output_id);
+		 output_type_name(pdo->output_type), output_id);
 
-	if (!(pdata = g_try_malloc0(sizeof(struct srd_proto_data)))) {
-		srd_err("Failed to g_malloc() struct srd_proto_data.");
-		return NULL;
-	}
+	pdata = g_malloc0(sizeof(struct srd_proto_data));
 	pdata->start_sample = start_sample;
 	pdata->end_sample = end_sample;
 	pdata->pdo = pdo;
@@ -256,12 +256,12 @@ static PyObject *Decoder_put(PyObject *self, PyObject *args)
 	case SRD_OUTPUT_PYTHON:
 		for (l = di->next_di; l; l = l->next) {
 			next_di = l->data;
-			srd_spew("Sending %d-%d to instance %s",
+			srd_spew("Sending %" PRIu64 "-%" PRIu64 " to instance %s",
 				 start_sample, end_sample, next_di->inst_id);
 			if (!(py_res = PyObject_CallMethod(
 				next_di->py_inst, "decode", "KKO", start_sample,
 				end_sample, py_data))) {
-				srd_exception_catch("Calling %s decode(): ",
+				srd_exception_catch("Calling %s decode() failed",
 							next_di->inst_id);
 			}
 			Py_XDECREF(py_res);
@@ -341,8 +341,7 @@ static PyObject *Decoder_register(PyObject *self, PyObject *args,
 		else if (meta_type_py == &PyFloat_Type)
 			meta_type_gv = G_VARIANT_TYPE_DOUBLE;
 		else {
-			PyErr_Format(PyExc_TypeError, "Unsupported type '%s'.",
-					meta_type_py->tp_name);
+			PyErr_Format(PyExc_TypeError, "Unsupported type.");
 			return NULL;
 		}
 	}
@@ -350,10 +349,7 @@ static PyObject *Decoder_register(PyObject *self, PyObject *args,
 	srd_dbg("Instance %s creating new output type %d for %s.",
 		di->inst_id, output_type, proto_id);
 
-	if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output)))) {
-		PyErr_SetString(PyExc_MemoryError, "struct srd_pd_output");
-		return NULL;
-	}
+	pdo = g_malloc(sizeof(struct srd_pd_output));
 
 	/* pdo_id is just a simple index, nothing is deleted from this list anyway. */
 	pdo->pdo_id = g_slist_length(di->pd_output);
@@ -381,13 +377,24 @@ static PyMethodDef Decoder_methods[] = {
 	{NULL, NULL, 0, NULL}
 };
 
-/** @cond PRIVATE */
-SRD_PRIV PyTypeObject srd_Decoder_type = {
-	PyVarObject_HEAD_INIT(NULL, 0)
-	.tp_name = "sigrokdecode.Decoder",
-	.tp_basicsize = sizeof(srd_Decoder),
-	.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
-	.tp_doc = "sigrok Decoder base class",
-	.tp_methods = Decoder_methods,
-};
-/** @endcond */
+/** Create the sigrokdecode.Decoder type.
+ * @return The new type object.
+ * @private
+ */
+SRD_PRIV PyObject *srd_Decoder_type_new(void)
+{
+	PyType_Spec spec;
+	PyType_Slot slots[] = {
+		{ Py_tp_doc, "sigrok Decoder base class" },
+		{ Py_tp_methods, Decoder_methods },
+		{ Py_tp_new, (void *)&PyType_GenericNew },
+		{ 0, NULL }
+	};
+	spec.name = "sigrokdecode.Decoder";
+	spec.basicsize = sizeof(srd_Decoder);
+	spec.itemsize = 0;
+	spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
+	spec.slots = slots;
+
+	return PyType_FromSpec(&spec);
+}
diff --git a/type_logic.c b/type_logic.c
index 4367680..d126d7b 100644
--- a/type_logic.c
+++ b/type_logic.c
@@ -17,8 +17,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+#include "libsigrokdecode.h"
 #include <inttypes.h>
 #include <string.h>
 
@@ -72,14 +73,25 @@ static PyObject *srd_logic_iternext(PyObject *self)
 	return logic->sample;
 }
 
-/** @cond PRIVATE */
-SRD_PRIV PyTypeObject srd_logic_type = {
-	PyVarObject_HEAD_INIT(NULL, 0)
-	.tp_name = "srd_logic",
-	.tp_basicsize = sizeof(srd_logic),
-	.tp_flags = Py_TPFLAGS_DEFAULT,
-	.tp_doc = "Sigrokdecode logic sample object",
-	.tp_iter = srd_logic_iter,
-	.tp_iternext = srd_logic_iternext,
-};
-/** @endcond */
+/** Create the srd_logic type.
+ * @return The new type object.
+ * @private
+ */
+SRD_PRIV PyObject *srd_logic_type_new(void)
+{
+	PyType_Spec spec;
+	PyType_Slot slots[] = {
+		{ Py_tp_doc, "sigrokdecode logic sample object" },
+		{ Py_tp_iter, (void *)&srd_logic_iter },
+		{ Py_tp_iternext, (void *)&srd_logic_iternext },
+		{ Py_tp_new, (void *)&PyType_GenericNew },
+		{ 0, NULL }
+	};
+	spec.name = "srd_logic";
+	spec.basicsize = sizeof(srd_logic);
+	spec.itemsize = 0;
+	spec.flags = Py_TPFLAGS_DEFAULT;
+	spec.slots = slots;
+
+	return PyType_FromSpec(&spec);
+}
diff --git a/util.c b/util.c
index 1efaa84..c3b84ab 100644
--- a/util.c
+++ b/util.c
@@ -18,49 +18,65 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
-#include "libsigrokdecode-internal.h"
-#include "config.h"
+#include <config.h>
+#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
+
+/**
+ * Import a Python module by name.
+ *
+ * This function is implemented in terms of PyImport_Import() rather than
+ * PyImport_ImportModule(), so that the import hooks are not bypassed.
+ *
+ * @param[in] name The name of the module to load as UTF-8 string.
+ * @return The Python module object, or NULL if an exception occurred. The
+ *  caller is responsible for evaluating and clearing the Python error state.
+ *
+ * @private
+ */
+SRD_PRIV PyObject *py_import_by_name(const char *name)
+{
+	PyObject *py_mod, *py_modname;
+
+	py_modname = PyUnicode_FromString(name);
+	if (!py_modname)
+		return NULL;
+
+	py_mod = PyImport_Import(py_modname);
+	Py_DECREF(py_modname);
+
+	return py_mod;
+}
 
 /**
  * Get the value of a Python object's attribute, returned as a newly
  * allocated char *.
  *
- * @param py_obj The object to probe.
- * @param attr Name of the attribute to retrieve.
- * @param outstr ptr to char * storage to be filled in.
+ * @param[in] py_obj The object to probe.
+ * @param[in] attr Name of the attribute to retrieve.
+ * @param[out] outstr ptr to char * storage to be filled in.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
- *         The 'outstr' argument points to a malloc()ed string upon success.
+ *         The 'outstr' argument points to a g_malloc()ed string upon success.
  *
  * @private
  */
-SRD_PRIV int py_attr_as_str(const PyObject *py_obj, const char *attr,
-			    char **outstr)
+SRD_PRIV int py_attr_as_str(PyObject *py_obj, const char *attr, char **outstr)
 {
 	PyObject *py_str;
 	int ret;
 
-	if (!PyObject_HasAttrString((PyObject *)py_obj, attr)) {
-		srd_dbg("%s object has no attribute '%s'.",
-			Py_TYPE(py_obj)->tp_name, attr);
+	if (!PyObject_HasAttrString(py_obj, attr)) {
+		srd_dbg("Object has no attribute '%s'.", attr);
 		return SRD_ERR_PYTHON;
 	}
 
-	if (!(py_str = PyObject_GetAttrString((PyObject *)py_obj, attr))) {
-		srd_exception_catch("");
-		return SRD_ERR_PYTHON;
-	}
-
-	if (!PyUnicode_Check(py_str)) {
-		srd_dbg("%s attribute should be a string, but is a %s.",
-			attr, Py_TYPE(py_str)->tp_name);
-		Py_DecRef(py_str);
+	if (!(py_str = PyObject_GetAttrString(py_obj, attr))) {
+		srd_exception_catch("Failed to get attribute '%s'", attr);
 		return SRD_ERR_PYTHON;
 	}
 
 	ret = py_str_as_str(py_str, outstr);
-	Py_DecRef(py_str);
+	Py_DECREF(py_str);
 
 	return ret;
 }
@@ -69,132 +85,185 @@ SRD_PRIV int py_attr_as_str(const PyObject *py_obj, const char *attr,
  * Get the value of a Python dictionary item, returned as a newly
  * allocated char *.
  *
- * @param py_obj The dictionary to probe.
- * @param key Key of the item to retrieve.
- * @param outstr Pointer to char * storage to be filled in.
+ * @param[in] py_obj The dictionary to probe.
+ * @param[in] key Key of the item to retrieve.
+ * @param[out] outstr Pointer to char * storage to be filled in.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
- *         The 'outstr' argument points to a malloc()ed string upon success.
+ *         The 'outstr' argument points to a g_malloc()ed string upon success.
  *
  * @private
  */
-SRD_PRIV int py_dictitem_as_str(const PyObject *py_obj, const char *key,
+SRD_PRIV int py_dictitem_as_str(PyObject *py_obj, const char *key,
 				char **outstr)
 {
 	PyObject *py_value;
-	int ret;
 
-	if (!PyDict_Check((PyObject *)py_obj)) {
-		srd_dbg("Object is a %s, not a dictionary.",
-			Py_TYPE((PyObject *)py_obj)->tp_name);
+	if (!PyDict_Check(py_obj)) {
+		srd_dbg("Object is not a dictionary.");
 		return SRD_ERR_PYTHON;
 	}
 
-	if (!(py_value = PyDict_GetItemString((PyObject *)py_obj, key))) {
+	if (!(py_value = PyDict_GetItemString(py_obj, key))) {
 		srd_dbg("Dictionary has no attribute '%s'.", key);
 		return SRD_ERR_PYTHON;
 	}
 
-	if (!PyUnicode_Check(py_value)) {
-		srd_dbg("Dictionary value for %s should be a string, but is "
-			"a %s.", key, Py_TYPE(py_value)->tp_name);
-		return SRD_ERR_PYTHON;
-	}
-
-	ret = py_str_as_str(py_value, outstr);
-
-	return ret;
+	return py_str_as_str(py_value, outstr);
 }
 
 /**
  * Get the value of a Python unicode string object, returned as a newly
  * allocated char *.
  *
- * @param py_str The unicode string object.
- * @param outstr ptr to char * storage to be filled in.
+ * @param[in] py_str The unicode string object.
+ * @param[out] outstr ptr to char * storage to be filled in.
  *
  * @return SRD_OK upon success, a (negative) error code otherwise.
- *         The 'outstr' argument points to a malloc()ed string upon success.
+ *         The 'outstr' argument points to a g_malloc()ed string upon success.
  *
  * @private
  */
-SRD_PRIV int py_str_as_str(const PyObject *py_str, char **outstr)
+SRD_PRIV int py_str_as_str(PyObject *py_str, char **outstr)
 {
-	PyObject *py_encstr;
-	int ret;
+	PyObject *py_bytes;
 	char *str;
 
-	py_encstr = NULL;
-	str = NULL;
-	ret = SRD_OK;
+	if (!PyUnicode_Check(py_str)) {
+		srd_dbg("Object is not a string object.");
+		return SRD_ERR_PYTHON;
+	}
 
-	if (!PyUnicode_Check((PyObject *)py_str)) {
-		srd_dbg("Object is a %s, not a string object.",
-			Py_TYPE((PyObject *)py_str)->tp_name);
-		ret = SRD_ERR_PYTHON;
-		goto err_out;
+	py_bytes = PyUnicode_AsUTF8String(py_str);
+	if (py_bytes) {
+		str = g_strdup(PyBytes_AsString(py_bytes));
+		Py_DECREF(py_bytes);
+		if (str) {
+			*outstr = str;
+			return SRD_OK;
+		}
 	}
+	srd_exception_catch("Failed to extract string");
+
+	return SRD_ERR_PYTHON;
+}
 
-	if (!(py_encstr = PyUnicode_AsEncodedString((PyObject *)py_str,
-	    "utf-8", NULL))) {
-		ret = SRD_ERR_PYTHON;
-		goto err_out;
+/**
+ * Convert a Python list of unicode strings to a C string vector.
+ * On success, a pointer to a newly allocated NULL-terminated array of
+ * allocated C strings is written to @a out_strv. The caller must g_free()
+ * each string and the array itself.
+ *
+ * @param[in] py_strseq The sequence object.
+ * @param[out] out_strv Address of string vector to be filled in.
+ *
+ * @return SRD_OK upon success, a (negative) error code otherwise.
+ *
+ * @private
+ */
+SRD_PRIV int py_strseq_to_char(PyObject *py_strseq, char ***out_strv)
+{
+	PyObject *py_item, *py_bytes;
+	char **strv, *str;
+	ssize_t seq_len, i;
+
+	if (!PySequence_Check(py_strseq)) {
+		srd_err("Object does not provide sequence protocol.");
+		return SRD_ERR_PYTHON;
 	}
-	if (!(str = PyBytes_AS_STRING(py_encstr))) {
-		ret = SRD_ERR_PYTHON;
-		goto err_out;
+
+	seq_len = PySequence_Size(py_strseq);
+	if (seq_len < 0) {
+		srd_exception_catch("Failed to obtain sequence size");
+		return SRD_ERR_PYTHON;
 	}
 
-	if (!(*outstr = g_strdup(str))) {
-		srd_dbg("Failed to g_malloc() outstr.");
-		ret = SRD_ERR_MALLOC;
-		goto err_out;
+	strv = g_try_new0(char *, seq_len + 1);
+	if (!strv) {
+		srd_err("Failed to allocate result string vector.");
+		return SRD_ERR_MALLOC;
 	}
 
-err_out:
-	if (py_encstr)
-		Py_XDECREF(py_encstr);
+	for (i = 0; i < seq_len; i++) {
+		py_item = PySequence_GetItem(py_strseq, i);
+		if (!py_item)
+			goto err_out;
+
+		if (!PyUnicode_Check(py_item)) {
+			Py_DECREF(py_item);
+			goto err_out;
+		}
+		py_bytes = PyUnicode_AsUTF8String(py_item);
+		Py_DECREF(py_item);
+		if (!py_bytes)
+			goto err_out;
 
-	if (PyErr_Occurred()) {
-		srd_exception_catch("string conversion failed");
+		str = g_strdup(PyBytes_AsString(py_bytes));
+		Py_DECREF(py_bytes);
+		if (!str)
+			goto err_out;
+
+		strv[i] = str;
 	}
+	*out_strv = strv;
 
-	return ret;
+	return SRD_OK;
+
+err_out:
+	g_strfreev(strv);
+	srd_exception_catch("Failed to obtain string item");
+
+	return SRD_ERR_PYTHON;
 }
 
 /**
- * Convert a Python list of unicode strings to a NULL-terminated UTF8-encoded
- * char * array. The caller must g_free() each string when finished.
- *
- * @param py_strlist The list object.
- * @param outstr ptr to char ** storage to be filled in.
+ * Convert a Python scalar object to a GLib variant.
+ * Supported variant types are string, int64 and double.
  *
- * @return SRD_OK upon success, a (negative) error code otherwise.
- *         The 'outstr' argument points to a g_malloc()ed char** upon success.
+ * @param[in] py_obj The Python object. Must not be NULL.
+ * @return A floating reference to a new variant, or NULL on failure.
  *
  * @private
  */
-SRD_PRIV int py_strseq_to_char(const PyObject *py_strseq, char ***outstr)
+SRD_PRIV GVariant *py_obj_to_variant(PyObject *py_obj)
 {
-	PyObject *py_str;
-	int list_len, i;
-	char **out, *str;
+	GVariant *var = NULL;
 
-	list_len = PySequence_Size((PyObject *)py_strseq);
-	if (!(out = g_try_malloc(sizeof(char *) * (list_len + 1)))) {
-		srd_err("Failed to g_malloc() 'out'.");
-		return SRD_ERR_MALLOC;
-	}
-	for (i = 0; i < list_len; i++) {
-		if (!(py_str = PyUnicode_AsEncodedString(
-		    PySequence_GetItem((PyObject *)py_strseq, i), "utf-8", NULL)))
-			return SRD_ERR_PYTHON;
-		if (!(str = PyBytes_AS_STRING(py_str)))
-			return SRD_ERR_PYTHON;
-		out[i] = g_strdup(str);
+	if (PyUnicode_Check(py_obj)) { /* string */
+		PyObject *py_bytes;
+		const char *str;
+
+		py_bytes = PyUnicode_AsUTF8String(py_obj);
+		if (py_bytes) {
+			str = PyBytes_AsString(py_bytes);
+			if (str)
+				var = g_variant_new_string(str);
+			Py_DECREF(py_bytes);
+		}
+		if (!var)
+			srd_exception_catch("Failed to extract string value");
+
+	} else if (PyLong_Check(py_obj)) { /* integer */
+		int64_t val;
+
+		val = PyLong_AsLongLong(py_obj);
+		if (!PyErr_Occurred())
+			var = g_variant_new_int64(val);
+		else
+			srd_exception_catch("Failed to extract integer value");
+
+	} else if (PyFloat_Check(py_obj)) { /* float */
+		double val;
+
+		val = PyFloat_AsDouble(py_obj);
+		if (!PyErr_Occurred())
+			var = g_variant_new_double(val);
+		else
+			srd_exception_catch("Failed to extract float value");
+
+	} else {
+		srd_err("Failed to extract value of unsupported type.");
 	}
-	out[i] = NULL;
-	*outstr = out;
 
-	return SRD_OK;
+	return var;
 }
diff --git a/version.c b/version.c
index 8fbbafa..699b3f5 100644
--- a/version.c
+++ b/version.c
@@ -18,6 +18,7 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  */
 
+#include <config.h>
 #include "libsigrokdecode.h"
 
 /**
diff --git a/version.h b/version.h
deleted file mode 100644
index 017bea7..0000000
--- a/version.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * This file is part of the libsigrokdecode project.
- *
- * Copyright (C) 2010 Uwe Hermann <uwe at hermann-uwe.de>
- * Copyright (C) 2012 Bert Vermeulen <bert at biot.com>
- *
- * 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 3 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, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef LIBSIGROKDECODE_VERSION_H
-#define LIBSIGROKDECODE_VERSION_H
-
-/**
- * @file
- *
- * Version number definitions and macros.
- */
-
-/**
- * @ingroup grp_versions
- *
- * @{
- */
-
-/*
- * Package version macros (can be used for conditional compilation).
- */
-
-/** The libsigrokdecode package 'major' version number. */
-#define SRD_PACKAGE_VERSION_MAJOR 0
-
-/** The libsigrokdecode package 'minor' version number. */
-#define SRD_PACKAGE_VERSION_MINOR 3
-
-/** The libsigrokdecode package 'micro' version number. */
-#define SRD_PACKAGE_VERSION_MICRO 0
-
-/** The libsigrokdecode package version ("major.minor.micro") as string. */
-#define SRD_PACKAGE_VERSION_STRING "0.3.0"
-
-/*
- * Library/libtool version macros (can be used for conditional compilation).
- */
-
-/** The libsigrokdecode libtool 'current' version number. */
-#define SRD_LIB_VERSION_CURRENT 2
-
-/** The libsigrokdecode libtool 'revision' version number. */
-#define SRD_LIB_VERSION_REVISION 0
-
-/** The libsigrokdecode libtool 'age' version number. */
-#define SRD_LIB_VERSION_AGE 0
-
-/** The libsigrokdecode libtool version ("current:revision:age") as string. */
-#define SRD_LIB_VERSION_STRING "2:0:0"
-
-/** @} */
-
-#endif
diff --git a/version.h.in b/version.h.in
index 5e78711..3053cef 100644
--- a/version.h.in
+++ b/version.h.in
@@ -38,32 +38,32 @@
  */
 
 /** The libsigrokdecode package 'major' version number. */
-#define SRD_PACKAGE_VERSION_MAJOR @SRD_PACKAGE_VERSION_MAJOR@
+#undef SRD_PACKAGE_VERSION_MAJOR
 
 /** The libsigrokdecode package 'minor' version number. */
-#define SRD_PACKAGE_VERSION_MINOR @SRD_PACKAGE_VERSION_MINOR@
+#undef SRD_PACKAGE_VERSION_MINOR
 
 /** The libsigrokdecode package 'micro' version number. */
-#define SRD_PACKAGE_VERSION_MICRO @SRD_PACKAGE_VERSION_MICRO@
+#undef SRD_PACKAGE_VERSION_MICRO
 
 /** The libsigrokdecode package version ("major.minor.micro") as string. */
-#define SRD_PACKAGE_VERSION_STRING "@SRD_PACKAGE_VERSION@"
+#undef SRD_PACKAGE_VERSION_STRING
 
 /*
  * Library/libtool version macros (can be used for conditional compilation).
  */
 
 /** The libsigrokdecode libtool 'current' version number. */
-#define SRD_LIB_VERSION_CURRENT @SRD_LIB_VERSION_CURRENT@
+#undef SRD_LIB_VERSION_CURRENT
 
 /** The libsigrokdecode libtool 'revision' version number. */
-#define SRD_LIB_VERSION_REVISION @SRD_LIB_VERSION_REVISION@
+#undef SRD_LIB_VERSION_REVISION
 
 /** The libsigrokdecode libtool 'age' version number. */
-#define SRD_LIB_VERSION_AGE @SRD_LIB_VERSION_AGE@
+#undef SRD_LIB_VERSION_AGE
 
 /** The libsigrokdecode libtool version ("current:revision:age") as string. */
-#define SRD_LIB_VERSION_STRING "@SRD_LIB_VERSION@"
+#undef SRD_LIB_VERSION_STRING
 
 /** @} */
 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/libsigrokdecode.git



More information about the debian-science-commits mailing list